-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

我不明白为什么会发生这种情况,将不胜感激。

4

2 回答 2

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

这证明了它是如何完全取决于机会的,我希望这会有所帮助!

于 2017-02-12T20:28:21.357 回答
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),并且对该列表进行排序,这就是为什么您多次获得它作为结果的原因。

这被称为鸽洞原理


对于您所做的事情,请考虑改用 sample

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
于 2017-02-12T20:29:05.867 回答