◐ Shell
clean mode source ↗

Fix int.from_bytes and Update random.py and test/test_random.py from CPython v3.11.2 by jyj0816 · Pull Request #4748 · RustPython/RustPython

Expand Up @@ -167,15 +167,11 @@ def seed(self, a=None, version=2): elif version == 2 and isinstance(a, (str, bytes, bytearray)): if isinstance(a, str): a = a.encode() a = int.from_bytes(a + _sha512(a).digest(), 'big') a = int.from_bytes(a + _sha512(a).digest())
elif not isinstance(a, (type(None), int, float, str, bytes, bytearray)): _warn('Seeding based on hashing is deprecated\n' 'since Python 3.9 and will be removed in a subsequent ' 'version. The only \n' 'supported seed types are: None, ' 'int, float, str, bytes, and bytearray.', DeprecationWarning, 2) raise TypeError('The only supported seed types are: None,\n' 'int, float, str, bytes, and bytearray.')
super().seed(a) self.gauss_next = None Expand Down Expand Up @@ -250,10 +246,8 @@ def __init_subclass__(cls, /, **kwargs): break
def _randbelow_with_getrandbits(self, n): "Return a random int in the range [0,n). Returns 0 if n==0." "Return a random int in the range [0,n). Defined for n > 0."
if not n: return 0 getrandbits = self.getrandbits k = n.bit_length() # don't use (n-1) here because n can be 1 r = getrandbits(k) # 0 <= r < 2**k Expand All @@ -262,7 +256,7 @@ def _randbelow_with_getrandbits(self, n): return r
def _randbelow_without_getrandbits(self, n, maxsize=1<<BPF): """Return a random int in the range [0,n). Returns 0 if n==0. """Return a random int in the range [0,n). Defined for n > 0.
The implementation does not use getrandbits, but only random. """ Expand All @@ -273,8 +267,6 @@ def _randbelow_without_getrandbits(self, n, maxsize=1<<BPF): "enough bits to choose from a population range this large.\n" "To remove the range limitation, add a getrandbits() method.") return _floor(random() * n) if n == 0: return 0 rem = maxsize % n limit = (maxsize - rem) / maxsize # int(limit * maxsize) % n == 0 r = random() Expand Down Expand Up @@ -303,10 +295,10 @@ def randbytes(self, n): ## -------------------- integer methods -------------------
def randrange(self, start, stop=None, step=_ONE): """Choose a random item from range(start, stop[, step]). """Choose a random item from range(stop) or range(start, stop[, step]).
This fixes the problem with randint() which includes the endpoint; in Python this is usually not what you want. Roughly equivalent to ``choice(range(start, stop, step))`` but supports arbitrarily large ranges and is optimized for common cases.
"""
Expand Down Expand Up @@ -387,37 +379,24 @@ def randint(self, a, b):
def choice(self, seq): """Choose a random element from a non-empty sequence.""" # raises IndexError if seq is empty return seq[self._randbelow(len(seq))]
def shuffle(self, x, random=None): """Shuffle list x in place, and return None.
Optional argument random is a 0-argument function returning a random float in [0.0, 1.0); if it is the default None, the standard random.random will be used. # As an accommodation for NumPy, we don't use "if not seq" # because bool(numpy.array()) raises a ValueError. if not len(seq): raise IndexError('Cannot choose from an empty sequence') return seq[self._randbelow(len(seq))]
""" def shuffle(self, x): """Shuffle list x in place, and return None."""
if random is None: randbelow = self._randbelow for i in reversed(range(1, len(x))): # pick an element in x[:i+1] with which to exchange x[i] j = randbelow(i + 1) x[i], x[j] = x[j], x[i] else: _warn('The *random* parameter to shuffle() has been deprecated\n' 'since Python 3.9 and will be removed in a subsequent ' 'version.', DeprecationWarning, 2) floor = _floor for i in reversed(range(1, len(x))): # pick an element in x[:i+1] with which to exchange x[i] j = floor(random() * (i + 1)) x[i], x[j] = x[j], x[i] randbelow = self._randbelow for i in reversed(range(1, len(x))): # pick an element in x[:i+1] with which to exchange x[i] j = randbelow(i + 1) x[i], x[j] = x[j], x[i]
def sample(self, population, k, *, counts=None): """Chooses k unique random elements from a population sequence or set. """Chooses k unique random elements from a population sequence.
Returns a new list containing elements from the population while leaving the original population unchanged. The resulting list is Expand Down Expand Up @@ -470,13 +449,8 @@ def sample(self, population, k, *, counts=None): # causing them to eat more entropy than necessary.
if not isinstance(population, _Sequence): if isinstance(population, _Set): _warn('Sampling from a set deprecated\n' 'since Python 3.9 and will be removed in a subsequent version.', DeprecationWarning, 2) population = tuple(population) else: raise TypeError("Population must be a sequence. For dicts or sets, use sorted(d).") raise TypeError("Population must be a sequence. " "For dicts or sets, use sorted(d).") n = len(population) if counts is not None: cum_counts = list(_accumulate(counts)) Expand Down Expand Up @@ -580,7 +554,7 @@ def triangular(self, low=0.0, high=1.0, mode=None): low, high = high, low return low + (high - low) * _sqrt(u * c)
def normalvariate(self, mu, sigma): def normalvariate(self, mu=0.0, sigma=1.0): """Normal distribution.
mu is the mean, and sigma is the standard deviation. Expand All @@ -601,7 +575,7 @@ def normalvariate(self, mu, sigma): break return mu + z * sigma
def gauss(self, mu, sigma): def gauss(self, mu=0.0, sigma=1.0): """Gaussian distribution.
mu is the mean, and sigma is the standard deviation. This is Expand Down Expand Up @@ -833,15 +807,15 @@ class SystemRandom(Random): """
def random(self): """Get the next random number in the range [0.0, 1.0).""" return (int.from_bytes(_urandom(7), 'big') >> 3) * RECIP_BPF """Get the next random number in the range 0.0 <= X < 1.0.""" return (int.from_bytes(_urandom(7)) >> 3) * RECIP_BPF
def getrandbits(self, k): """getrandbits(k) -> x. Generates an int with k random bits.""" if k < 0: raise ValueError('number of bits must be non-negative') numbytes = (k + 7) // 8 # bits / 8 and rounded up x = int.from_bytes(_urandom(numbytes), 'big') x = int.from_bytes(_urandom(numbytes)) return x >> (numbytes * 8 - k) # trim excess bits
def randbytes(self, n): Expand Down