为什么我的随机列表中的值总是相同的?

Why are the values in my random list are always the same?

此代码用于最大成对乘积,我一直在对其进行测试,但遇到了一些问题。

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

我不明白为什么会这样,如果有解释,我们将不胜感激。

发生这种情况是因为您正在对列表进行排序,因此最大的数字排在最后。列表键将包含数十万个数字,并且由于只有 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

这说明了它是如何完全取决于偶然性的,希望对您有所帮助!

问题出在你的 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