is there a way to let the program select a random number between say 1 and 1,000 without importing random
?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With