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?
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?
>>> import random
>>> random.getrandbits(10)
688L
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.