MCPcopy Index your code
hub / github.com/python/cpython / randrange

Method randrange

Lib/random.py:294–333  ·  view source on GitHub ↗

Choose a random item from range(stop) or range(start, stop[, step]). Roughly equivalent to ``choice(range(start, stop, step))`` but supports arbitrarily large ranges and is optimized for common cases.

(self, start, stop=None, step=_ONE)

Source from the content-addressed store, hash-verified

292 ## -------------------- integer methods -------------------
293
294 def randrange(self, start, stop=None, step=_ONE):
295 """Choose a random item from range(stop) or range(start, stop[, step]).
296
297 Roughly equivalent to ``choice(range(start, stop, step))`` but
298 supports arbitrarily large ranges and is optimized for common cases.
299
300 """
301
302 # This code is a bit messy to make it fast for the
303 # common case while still doing adequate error checking.
304 istart = _index(start)
305 if stop is None:
306 # We don't check for "step != 1" because it hasn't been
307 # type checked and converted to an integer yet.
308 if step is not _ONE:
309 raise TypeError("Missing a non-None stop argument")
310 if istart > 0:
311 return self._randbelow(istart)
312 raise ValueError("empty range for randrange()")
313
314 # Stop argument supplied.
315 istop = _index(stop)
316 width = istop - istart
317 istep = _index(step)
318 # Fast path.
319 if istep == 1:
320 if width > 0:
321 return istart + self._randbelow(width)
322 raise ValueError(f"empty range in randrange({start}, {stop})")
323
324 # Non-unit step argument supplied.
325 if istep > 0:
326 n = (width + istep - 1) // istep
327 elif istep < 0:
328 n = (width + istep + 1) // istep
329 else:
330 raise ValueError("zero step for randrange()")
331 if n <= 0:
332 raise ValueError(f"empty range in randrange({start}, {stop}, {step})")
333 return istart + istep * self._randbelow(n)
334
335 def randint(self, a, b):
336 """Return random integer in range [a, b], including both end points.

Callers 15

_make_boundaryMethod · 0.80
test_delitemMethod · 0.80
test_internMethod · 0.80
test_halfway_casesMethod · 0.80
test_boundariesMethod · 0.80
test_bigcompMethod · 0.80
test_parsingMethod · 0.80
test_funcFunction · 0.80

Calls 1

_indexFunction · 0.85

Tested by 15

test_delitemMethod · 0.64
test_internMethod · 0.64
test_halfway_casesMethod · 0.64
test_boundariesMethod · 0.64
test_bigcompMethod · 0.64
test_parsingMethod · 0.64
test_funcFunction · 0.64