summaryrefslogtreecommitdiffstats
path: root/Lib/random.py
diff options
context:
space:
mode:
authorRaymond Hettinger <rhettinger@users.noreply.github.com>2025-02-21 17:33:10 (GMT)
committerGitHub <noreply@github.com>2025-02-21 17:33:10 (GMT)
commit286c517db0fedf8d923d6f9620bcbbac4333880d (patch)
tree5b131be7c075da4bc2e1c59e08d3f62164ec7fcc /Lib/random.py
parent0c4248f88e279df3254d62b34dfa3204a92c56a0 (diff)
downloadcpython-286c517db0fedf8d923d6f9620bcbbac4333880d.zip
cpython-286c517db0fedf8d923d6f9620bcbbac4333880d.tar.gz
cpython-286c517db0fedf8d923d6f9620bcbbac4333880d.tar.bz2
gh-130285: Fix handling of zero or empty counts in random.sample() (gh-130291)
Diffstat (limited to 'Lib/random.py')
-rw-r--r--Lib/random.py6
1 files changed, 3 insertions, 3 deletions
diff --git a/Lib/random.py b/Lib/random.py
index 8b9a270..1abcae7 100644
--- a/Lib/random.py
+++ b/Lib/random.py
@@ -421,11 +421,11 @@ class Random(_random.Random):
cum_counts = list(_accumulate(counts))
if len(cum_counts) != n:
raise ValueError('The number of counts does not match the population')
- total = cum_counts.pop()
+ total = cum_counts.pop() if cum_counts else 0
if not isinstance(total, int):
raise TypeError('Counts must be integers')
- if total <= 0:
- raise ValueError('Total of counts must be greater than zero')
+ if total < 0:
+ raise ValueError('Counts must be non-negative')
selections = self.sample(range(total), k=k)
bisect = _bisect
return [population[bisect(cum_counts, s)] for s in selections]