bpo-38881: choices() raises ValueError when all weights are zero (GH-17362)

This commit is contained in:
Raymond Hettinger 2019-11-23 02:22:13 -08:00 committed by GitHub
parent 84b1ff6560
commit 041d8b48a2
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
4 changed files with 15 additions and 3 deletions

View file

@ -413,8 +413,10 @@ class Random(_random.Random):
raise TypeError('Cannot specify both weights and cumulative weights')
if len(cum_weights) != n:
raise ValueError('The number of weights does not match the population')
bisect = _bisect
total = cum_weights[-1] + 0.0 # convert to float
if total <= 0.0:
raise ValueError('Total of weights must be greater than zero')
bisect = _bisect
hi = n - 1
return [population[bisect(cum_weights, random() * total, 0, hi)]
for i in _repeat(None, k)]