mirror of
https://github.com/python/cpython.git
synced 2025-07-09 20:35:26 +00:00
Move error test to the function that needs it. Improve error message. (GH-30008)
This commit is contained in:
parent
50669083fe
commit
3fee7776e6
2 changed files with 4 additions and 11 deletions
|
@ -233,10 +233,8 @@ class Random(_random.Random):
|
|||
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
|
||||
|
@ -245,7 +243,7 @@ class Random(_random.Random):
|
|||
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.
|
||||
"""
|
||||
|
@ -256,8 +254,6 @@ class Random(_random.Random):
|
|||
"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()
|
||||
|
@ -338,7 +334,8 @@ class Random(_random.Random):
|
|||
|
||||
def choice(self, seq):
|
||||
"""Choose a random element from a non-empty sequence."""
|
||||
# raises IndexError if seq is empty
|
||||
if not seq:
|
||||
raise IndexError('Cannot choose from an empty sequence')
|
||||
return seq[self._randbelow(len(seq))]
|
||||
|
||||
def shuffle(self, x):
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue