简体   繁体   English

random.randint多久生成一次相同的数字?

[英]How often does random.randint generate the same number?

I want to generate random integers between 0-9 (inclusive on both ends), but I want to make sure it doesn't often generate the same number consecutively. 我想生成介于0到9之间(包括两端)的随机整数,但是我想确保它不会经常连续生成相同的数字。 I plan to use the randint function from the random module. 我计划使用random模块中的randint函数。 But I'm not sure if it will be handy. 但是我不确定是否会方便。 How often does random.randint generate the same number? random.randint多久生成一次相同的数字?

Why not wrap randint? 为什么不包装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()
...

Where the Python docs say random you can assume they mean uniformly random unless stated otherwise (that is, all possible outcomes have equal probability). Python文档随机的地方除非另有说明(即所有可能的结果具有相等的概率),否则您可以假设它们的意思是统一随机的。

In order to generate numbers without consecutive numbers being generated, the simplest option is to make your own generator: 为了生成数字而不生成连续的数字,最简单的选择是制作自己的生成器:

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

To avoid duplicates you can use a simple wrapper like this (see Fisher–Yates for explanations on how this works): 为了避免重复,您可以使用像这样的简单包装器(有关其工作原理的说明,请参见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]

Example of use: 使用示例:

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

无需while循环即可轻松完成此操作。

next_random_number = (previous_random_number + random.randint(1,9)) % 10
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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM