從python docs,「set.pop()移除並返回s中的任意元素」。在生成一些隨機數據來測試程序時,我注意到了這個pop()函數的奇怪行爲。這裏是我的代碼(蟒蛇2.7.3):Set.pop()不是隨機的嗎?
testCases = 10
numberRange = 500
poppedValues = []
greaterPercentages = []
for i in range (testCases):
s = Set()
""" inserting 100 random values in the set, in the range [0, numberRange) """
for j in range (100):
s.add(random.randrange(numberRange))
poppedValue = s.pop()
greaterCount = 0
""" counting how many numbers in the set are smaller then the popped value """
for number in s:
if poppedValue > number:
greaterCount += 1
poppedValues.append(poppedValue)
greaterPercentages.append(float(greaterCount)/len(s) * 100)
for poppedValue in poppedValues:
print poppedValue, '\t',
print
for percentage in greaterPercentages:
print "{:2.2f}".format(percentage), '\t',
什麼,我就是在這裏做,
- 在集
s
每個元素的範圍是[0插入一些隨機值,numberRange
) - 從集合彈出的元件(根據該文檔,它應該是一個隨機的一個)
- 計數在設定的許多元素是如何小,則彈出值
我預計彈出的值應該是隨機的,並且集合中大約50%的數字將大於彈出的值。但似乎pop()
幾乎總是返回集合中的最低數字。這裏是numberRange = 500
的結果。第一行表示彈出元素的值。第二行是比彈出的值小的元素的百分比。
9 0 3 1 409 0 1 2 4 0
0 % 0 % 0 % 0 % 87 % 0 % 0 % 0 % 0 % 0 %
我已經用不同的值numberRange
進行了這個測試。似乎對於設置元素的較低值,pop()
幾乎總是返回最低元素。但是對於更高的值,它會返回一個隨機元素。對於numberRange = 1000
,結果是:
518 3586 3594 4103 2560 3087 4095 3079 3076 1622
7 % 72 % 73 % 84 % 54 % 51 % 79 % 63 % 67 % 32 %
我認爲這是非常隨機的。爲什麼這個奇怪的行爲難道我做錯了什麼?
編輯:感謝大家的回答和評論,似乎通過「任意」,它不能保證它是「隨機的」。
這不是隨機的,它是無序的。 – Matthias
「隨意」的文檔並不意味着「隨機」,它們的意思是「不依賴於任何特定的值,實施細節可能會在沒有警告的情況下發生變化」 – wim
隨機並不意味着它的分佈非常好,甚至不可預知。這意味着你將來不能依賴任何觀察。 – Alfe