mirror of
https://github.com/python/cpython.git
synced 2025-10-09 08:31:26 +00:00
Simplify choice()'s interaction with the private _randbelow() method (GH-19831)
This commit is contained in:
parent
03b7642265
commit
4168f1e460
2 changed files with 8 additions and 12 deletions
|
@ -265,10 +265,10 @@ class Random(_random.Random):
|
|||
return self.randrange(a, b+1)
|
||||
|
||||
def _randbelow_with_getrandbits(self, n):
|
||||
"Return a random int in the range [0,n). Raises ValueError if n==0."
|
||||
"Return a random int in the range [0,n). Returns 0 if n==0."
|
||||
|
||||
if not n:
|
||||
raise ValueError("Boundary cannot be zero")
|
||||
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
|
||||
|
@ -277,7 +277,7 @@ class Random(_random.Random):
|
|||
return r
|
||||
|
||||
def _randbelow_without_getrandbits(self, n, int=int, maxsize=1<<BPF):
|
||||
"""Return a random int in the range [0,n). Raises ValueError if n==0.
|
||||
"""Return a random int in the range [0,n). Returns 0 if n==0.
|
||||
|
||||
The implementation does not use getrandbits, but only random.
|
||||
"""
|
||||
|
@ -289,7 +289,7 @@ class Random(_random.Random):
|
|||
"To remove the range limitation, add a getrandbits() method.")
|
||||
return int(random() * n)
|
||||
if n == 0:
|
||||
raise ValueError("Boundary cannot be zero")
|
||||
return 0
|
||||
rem = maxsize % n
|
||||
limit = (maxsize - rem) / maxsize # int(limit * maxsize) % n == 0
|
||||
r = random()
|
||||
|
@ -303,11 +303,7 @@ class Random(_random.Random):
|
|||
|
||||
def choice(self, seq):
|
||||
"""Choose a random element from a non-empty sequence."""
|
||||
try:
|
||||
i = self._randbelow(len(seq))
|
||||
except ValueError:
|
||||
raise IndexError('Cannot choose from an empty sequence') from None
|
||||
return seq[i]
|
||||
return seq[self._randbelow(len(seq))] # raises IndexError if seq is empty
|
||||
|
||||
def shuffle(self, x, random=None):
|
||||
"""Shuffle list x in place, and return None.
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue