2017-02-12 107 views
-1

此代碼是針對最大成對產品的,我一直在測試它,但我遇到了一些問題。爲什麼我的隨機列表中的值總是相同的?

import sys 
import random 
while True: 
    a=int(random.randrange(1,1000000,101)) 
    keys =[]  # keys is empety list 
    i=0 

    while i < a : 
     keys.append(int(random.randrange(1,10000,8))) 
     i=i+1 

    keys.sort() 
    print(keys[-1], keys[-2]) 
    x=keys[-1]*keys[-2] 
    print("the max is ",x) 

但是,由於某些原因,代碼的輸出總是相同的。

9993 9993 
the max is 99860049 
9993 9993 
the max is 99860049 
9993 9993 
the max is 99860049 
9993 9993 
the max is 99860049 

我不明白爲什麼會發生這種情況,一個解釋將不勝感激。

+0

EUH的'keys'是相同的,以及... –

回答

0

發生這種情況是因爲您正在對您的列表進行排序,因此最大的數字在最後。列表鍵將包含數十萬個數字,並且由於只有1249個可能的鍵(9993 - 1)/8 = 1249,您很可能會得到兩個最大可能數9993的實例。但是,情況並非總是如此,當我跑了你的代碼有一次我得到了不同的結果:

9993 9993 
the max is 99860049 
9993 9993 
the max is 99860049 
9977 9969 #<-- Not 9993 
the max is 99460713 
9993 9993 
the max is 99860049 

這說明它是如何純屬下來的機會,我希望這有助於!

+0

現在我的代碼有一點變化,以確保錯誤消失,我已經取代d'random.radrange()'with'random.randint()' –

+0

thanx您的幫助 –

0

的問題是你a,太大了,如果你硬編碼說100,那麼你得到的慾望行爲

9945 9857 
the max is 98027865 
9905 9881 
the max is 97871305 
9969 9881 
the max is 98503689 
9977 9849 
the max is 98263473 
9977 9945 
the max is 99221265 
9713 9617 
the max is 93409921 
9993 9977 
the max is 99700161 
9929 9841 
the max is 97711289 
9881 9761 
the max is 96448441 
9953 9841 

您選擇a作爲

>>> random.randrange(1,1000000,101) 
18181 
>>> random.randrange(1,1000000,101) 
835069 
>>> random.randrange(1,1000000,101) 
729524 
>>> 

而選擇你的鑰匙從一個只池

>>> len(range(1, 10000, 8)) 
1250 
>>> 

(或多或少一個)

只有1250個不同的元素可供選擇,當你經常採取比這更多的(比如18181)時,你會得到該範圍內所有可能的數字(幾次),因此你總能得到相同的結果結果,並有這麼多的嘗試,你幾乎可以保證得到該範圍內的最大數字(9993)幾次,並作爲排序列表,這就是爲什麼你得到它作爲你的結果很多次。

這是知道作爲Pigeonhole principle


爲你做什麼,可以考慮使用替代樣本

for _ in range(5): 
    a,b = random.sample(range(1,10000,8),2) 
    print(a,b) 
    print("the max is ",a*b) 

輸出

2881 689 
the max is 1985009 
2329 6473 
the max is 15075617 
5953 7769 
the max is 46248857 
9905 3201 
the max is 31705905 
6897 4713 
the max is 32505561 
相關問題