Looking at the various random functions in the standard library, there isn't a way to generate numbers of n-bit length long.
Is there any efficient function I can use to accomplish this?
To generate random number in Python, randint() function is used. This function is defined in random module.
Use randint() Generate random integer randint() function to get a random integer number from the inclusive range. For example, random. randint(0, 10) will return a random number from [0, 1, 2, 3, 4, 5, 6, 7, 8 ,9, 10].
The function randint() generates random integers for you. If you call the function, it returns a random integer N such that a <= N <= b . The randint() method to generates a whole number (integer). You can use randint(0,50) to generate a random number between 0 and 50.
Yes there is:
>>> import random
>>> random.getrandbits(1)
0L
>>> random.getrandbits(100)
31456252575598781139680104123L
>>> help(random.getrandbits)
Help on built-in function getrandbits:
getrandbits(...)
getrandbits(k) -> x. Generates a long int with k random bits.
From the docs:
random.getrandbits(k)
Returns a python long int withk
random bits. This method is supplied with the MersenneTwister generator and some other generators may also provide it as an optional part of the API. When available,getrandbits()
enablesrandrange()
to handle arbitrarily large ranges.
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