[docs] weighted random choice doc bug

Noah Levitt nlevitt at archive.org
Wed Sep 7 15:16:37 EDT 2016


There's a bug in the general approach to weighted random choice at the
bottom of https://docs.python.org/3.6/library/random.html. This is
what happens if all the weights are zero (a real possibility):

>>> import itertools, random, bisect
>>> weighted_choices = [('Red', 0), ('Blue', 0), ('Yellow', 0), ('Green', 0)]
>>> choices, weights = zip(*weighted_choices)
>>> cumdist = list(itertools.accumulate(weights))
>>> cumdist
[0, 0, 0, 0]
>>> x = random.random() * cumdist[-1]
>>> bisect.bisect(cumdist, x)
4
>>> choices[bisect.bisect(cumdist, x)]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IndexError: tuple index out of range

I think changing the bisect.bisect() call to bisect.bisect_left() is a
correct fix.

Noah


More information about the docs mailing list