随机int而不导入'随机' [英] Random int without importing 'random'
本文介绍了随机int而不导入'随机'的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
有没有办法让程序选择1到1,000之间的随机数而不导入'随机'?
is there a way to let the program select a random number between say 1 and 1,000 without importing 'random'?
非常感谢帮助。
推荐答案
基于 随机
源代码:
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)
示例:
print(randint(1, 1000))
你也可以实施 random_bytes()
使用PRNG 。
You could also implement random_bytes()
using PRNG.
这篇关于随机int而不导入'随机'的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文