random number without random module

Solutions on MaxInterview for random number without random module by the best coders in the world

showing results for - "random number without random module"
Emilio
03 Jan 2021
1# First let's make a function that makes a random number 
2
3def randint(a, b):
4    "Return random integer in range [a, b], including both end points."
5    return a + randbelow(b - a + 1)
6
7def randbelow(n):
8    "Return a random int in the range [0,n).  Raises ValueError if n<=0."
9    k = n.bit_length()
10    numbytes = (k + 7) // 8
11    while True:
12        r = int.from_bytes(random_bytes(numbytes), 'big')
13        r >>= numbytes * 8 - k
14        if r < n:
15            return r
16
17def random_bytes(n):
18    "Return n random bytes"
19    with open('/dev/urandom', 'rb') as file:
20        return file.read(n)
21
similar questions
queries leading to this page
random number without random module