summaryrefslogtreecommitdiffstats
path: root/Lib
diff options
context:
space:
mode:
Diffstat (limited to 'Lib')
-rw-r--r--Lib/random.py4
-rw-r--r--Lib/test/test_random.py5
2 files changed, 8 insertions, 1 deletions
diff --git a/Lib/random.py b/Lib/random.py
index be4401c..e24737d 100644
--- a/Lib/random.py
+++ b/Lib/random.py
@@ -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)]
diff --git a/Lib/test/test_random.py b/Lib/test/test_random.py
index f59c565..2c8c8e8 100644
--- a/Lib/test/test_random.py
+++ b/Lib/test/test_random.py
@@ -241,6 +241,11 @@ class TestBasicOps:
choices = self.gen.choices
choices(population=[1, 2], weights=[1e-323, 1e-323], k=5000)
+ def test_choices_with_all_zero_weights(self):
+ # See issue #38881
+ with self.assertRaises(ValueError):
+ self.gen.choices('AB', [0.0, 0.0])
+
def test_gauss(self):
# Ensure that the seed() method initializes all the hidden state. In
# particular, through 2.2.1 it failed to reset a piece of state used