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. I plan to use the randint
function from the random
module. But I'm not sure if it will be handy. How often does random.randint
generate the same number?
Why not wrap 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).
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):
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)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.