随机int而不导入'随机'

use*_*391 8 python random import python-3.x

有没有办法让程序选择1到1000之间的随机数而不导入'随机'?

非常感谢帮助.

jfs*_*jfs 8

基于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)
Run Code Online (Sandbox Code Playgroud)

例:

print(randint(1, 1000))
Run Code Online (Sandbox Code Playgroud)

您也可以使用PRNG 实现random_bytes().


Bac*_*ics 1

假设你想要整数。

import numpy as np
np.random.randint(1,1000)
Run Code Online (Sandbox Code Playgroud)

  • 我会让你付钱给我来得到答案,但那样你就将在余生中这样做。太糟糕了。享受你的家庭作业。**提示**阅读此https://docs.python.org/2/library/datetime.html (2认同)