Issue 31689: random.choices does not work with negative weights (original) (raw)

Code to reproduce problem:

population = list(range(10)) weights = list(-1 * w for w in range(10)) [random.choices(population, weights) for _ in range(1000)]

will raise IndexError:

358         bisect = _bisect.bisect
359         total = cum_weights[-1]

--> 360 return [population[bisect(cum_weights, random() * total)] for i in range(k)] 361 362 ## -------------------- real-valued distributions -------------------

IndexError: list index out of range

I think this should be reopened, as the behavior doesn't always raise an error, and, in fact, does something very unexpected:

Python 3.7.2 (default, Jan 13 2019, 12:50:01) [Clang 10.0.0 (clang-1000.11.45.5)] on darwin Type "help", "copyright", "credits" or "license" for more information.

from collections import Counter from random import choices Counter(choices("abcdefg", weights=(1,1,-1,1,1,0,1), k=10000)) Counter({'a': 2569, 'b': 2514, 'e': 2487, 'g': 2430})

It's really not clear to me why supplying a negative weight for "c" should have any effect on "d".