Skip to content
Merged
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Next Next commit
index() version
  • Loading branch information
rhettinger committed Oct 15, 2021
commit eb76fbd95562b3a6e4fef0cb53be84ace4928e5c
30 changes: 14 additions & 16 deletions Lib/random.py
Original file line number Diff line number Diff line change
Expand Up @@ -97,6 +97,7 @@
SG_MAGICCONST = 1.0 + _log(4.5)
BPF = 53 # Number of bits in a float
RECIP_BPF = 2 ** -BPF
_ONE = 1


class Random(_random.Random):
Expand Down Expand Up @@ -284,7 +285,7 @@ def randbytes(self, n):

## -------------------- integer methods -------------------

def randrange(self, start, stop=None, step=1):
def randrange(self, start, stop=None, step=_ONE):
"""Choose a random item from range(start, stop[, step]).

This fixes the problem with randint() which includes the
Expand All @@ -294,38 +295,35 @@ def randrange(self, start, stop=None, step=1):

# This code is a bit messy to make it fast for the
# common case while still doing adequate error checking.
istart = int(start)
if istart != start:
raise ValueError("non-integer arg 1 for randrange()")
istart = _index(start)
if stop is None:
# We don't check for "step != 1" because it hasn't been
# type checked and converted to an integer yet.
if step is not _ONE:
raise TypeError('Missing a non-None stop argument')
if istart > 0:
return self._randbelow(istart)
raise ValueError("empty range for randrange()")

# stop argument supplied.
istop = int(stop)
if istop != stop:
raise ValueError("non-integer stop for randrange()")
# Stop argument supplied.
istop = _index(stop)
width = istop - istart
if step == 1 and width > 0:
return istart + self._randbelow(width)
if step == 1:
istep = _index(step)
# Fast path.
if istep == 1:
if width > 0:
return istart + self._randbelow(width)
raise ValueError("empty range for randrange() (%d, %d, %d)" % (istart, istop, width))

# Non-unit step argument supplied.
istep = int(step)
if istep != step:
raise ValueError("non-integer step for randrange()")
if istep > 0:
n = (width + istep - 1) // istep
elif istep < 0:
n = (width + istep + 1) // istep
else:
raise ValueError("zero step for randrange()")

if n <= 0:
raise ValueError("empty range for randrange()")

return istart + istep * self._randbelow(n)

def randint(self, a, b):
Expand Down