2017-02-12 102 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 
相关问题