Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Random int without importing 'random'

is there a way to let the program select a random number between say 1 and 1,000 without importing random?

like image 971
user3353391 Avatar asked Apr 09 '14 00:04

user3353391


Video Answer


1 Answers

Based on random source code:

def randint(a, b):
    "Return random integer in range [a, b], including both end points."
    return a + randbelow(b - a + 1)

def randbelow(n):
    "Return a random int in the range [0,n).  Raises ValueError if n<=0."
    if n <= 0:
       raise ValueError
    k = n.bit_length()
    numbytes = (k + 7) // 8
    while True:
        r = int.from_bytes(random_bytes(numbytes), 'big')
        r >>= numbytes * 8 - k
        if r < n:
            return r

def random_bytes(n):
    "Return n random bytes"
    with open('/dev/urandom', 'rb') as file:
        return file.read(n)

Example:

print(randint(1, 1000))

You could also implement random_bytes() using PRNG.

like image 137
jfs Avatar answered Nov 12 '22 11:11

jfs