【问题标题】:Why are the values in my random list are always the same?为什么我的随机列表中的值总是相同的?
【发布时间】:2017-02-12 20:00:37
【问题描述】:

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

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

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

【问题讨论】:

  • keys也一样...

标签: python python-3.x code-testing


【解决方案1】:

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

这证明了它是如何完全靠运气的,我希望这会有所帮助!

【讨论】:

  • 现在我对我的代码进行了一些更改,以确保错误会消失我已将 random.radrange() 替换为 random.randint()
  • 感谢您的帮助
【解决方案2】:

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

【讨论】:

    猜你喜欢
    • 2014-05-18
    • 1970-01-01
    相关资源
    最近更新 更多