【问题标题】:How often does random.randint generate the same number?random.randint 多久生成一次相同的数字?
【发布时间】:2012-06-21 07:25:04
【问题描述】:

我想生成 0-9 之间的随机整数(包括两端),但我想确保它不会经常连续生成相同的数字。我打算使用random 模块中的randint 函数。但我不确定它是否会派上用场。 random.randint 多久生成一次相同的数字?

【问题讨论】:

  • 假设足够随机,两次得到相同数字的概率为10%。

标签: python random integer


【解决方案1】:
list =[]
x=0
for i in range(0,10):
    while x in list:
        x=random.randint(500,1000)
    list.append(x)
print sorted(list, key=int)

【讨论】:

  • 请解释一下你的答案。From review.
  • 你好,你可以使用列表生成随机数而不是重复
【解决方案2】:

如果the Python docs随机,您可以假设它们的意思是一致随机的,除非另有说明(即所有可能的结果具有相同的概率)。

为了在不生成连续数字的情况下生成数字,最简单的选择是制作自己的生成器:

def random_non_repeating(min, max=None):
    if not max:
        min, max = 0, min
    old = None
    while True:
        current = random.randint(min, max)
        if not old == current:
            old = current
            yield current

【讨论】:

    【解决方案3】:

    这很容易在没有 while 循环的情况下完成。

    next_random_number = (previous_random_number + random.randint(1,9)) % 10
    

    【讨论】:

    • 这是一种简洁高效的方式。
    【解决方案4】:

    为避免重复,您可以使用这样的简单包装器(有关其工作原理的说明,请参阅 Fisher–Yates):

    def unique_random(choices):
        while True:
            r = random.randrange(len(choices) - 1) + 1
            choices[0], choices[r] = choices[r], choices[0]
            yield choices[0]
    

    使用示例:

    from itertools import islice
    g = unique_random(range(10))
    print list(islice(g, 100))
    

    【讨论】:

    • 我觉得使用生成器获取随机数并不自然。
    • 你为什么要通过islice100?如果你想让它走到最后,只需传递None
    • @Lattyware 使用生成器获取单个随机数的语法很麻烦。
    • @Lattyware:目的是什么?没完没了。
    • @robert:问题是关于生成随机数的非重复序列
    【解决方案5】:

    为什么不包装 randint?

    class MyRand(object):
        def __init__(self):
            self.last = None
    
        def __call__(self):
            r = random.randint(0, 9)
            while r == self.last:
                r = random.randint(0, 9)
            self.last = r
            return r
    
    randint = MyRand()
    x = randint()
    y = randint()
    ...
    

    【讨论】:

    • 哇,我完全错过了问题的避免重复、连续生成部分,+1。
    • 也就是说,我确实觉得生成器在这里是一个更优雅的解决方案。
    猜你喜欢
    • 2021-07-11
    • 1970-01-01
    • 1970-01-01
    • 2010-12-23
    • 1970-01-01
    • 2014-11-13
    • 1970-01-01
    • 1970-01-01
    • 2021-11-03
    相关资源
    最近更新 更多