Python 为什么我的随机列表中的值总是相同的?
这段代码是针对最大成对产品的,我一直在测试它,但我遇到了一些问题Python 为什么我的随机列表中的值总是相同的?,python,python-3.x,code-testing,Python,Python 3.x,Code Testing,这段代码是针对最大成对产品的,我一直在测试它,但我遇到了一些问题 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
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)
我不明白为什么会发生这种情况,请给出解释。之所以会发生这种情况,是因为您正在对列表进行排序,以便将最大的数字排在最后。列表键将包含数十万个数字,并且由于只有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
999393
最大值为99860049
9993 9993
最大值为99860049
99779969#问题是你的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)几次,并对列表进行排序,这就是为什么您多次将其作为结果
这被称为
对于你所做的,考虑使用样本代替
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
嗯,键
也是一样的……现在我对我的代码做了一些更改,以确保错误消失。我已将random.radrange()
替换为random.randint()
thanx,谢谢您的帮助
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