python set 随机_python – Set.pop()不是随机的吗?
從
python docs開始,“set.pop()從s中刪除并返回一個任意元素”.在生成一些隨機數據來測試程序時,我注意到這個pop()函數的奇怪行為.這是我的代碼(python 2.7.3):
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',
for percentage in greaterPercentages:
print "{:2.2f}".format(percentage), '\t',
我在這里做的是,
>在集合中插入一些隨機值,其中每個元素的范圍為[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值進行了這個測試.似乎對于set元素的較低值,pop()幾乎總是返回最低元素.但是對于更高的值,它返回一個隨機元素.對于numberRange = 1000,結果是:
518 3586 3594 4103 2560 3087 4095 3079 3076 1622
7 % 72 % 73 % 84 % 54 % 51 % 79 % 63 % 67 % 32 %
我覺得這很隨意.為何這種奇怪的行為?難道我做錯了什么?
編輯:感謝大家的回答和評論,似乎“任意”,它不能保證它是“隨機的”.
總結
以上是生活随笔為你收集整理的python set 随机_python – Set.pop()不是随机的吗?的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: D进制的A+B (20)
- 下一篇: python 结构数组_Python-“