random choice without random module

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

showing results for - "random choice without random module"
Sarah
02 Oct 2019
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
22list = ["Hello", "No", "Poop", "Ok", "Bruh", "LOL"]
23lenlist = len(list)
24random_num_that_we_will_use_to_get_an_element_from_list = randint(1, lenlist)
25print(list[random_num_that_we_will_use_to_get_an_element_from_list - 1])