Skip to content

Commit 286c517

Browse files
authored
gh-130285: Fix handling of zero or empty counts in random.sample() (gh-130291)
1 parent 0c4248f commit 286c517

File tree

3 files changed

+21
-5
lines changed

3 files changed

+21
-5
lines changed

Lib/random.py

+3-3
Original file line numberDiff line numberDiff line change
@@ -421,11 +421,11 @@ def sample(self, population, k, *, counts=None):
421421
cum_counts = list(_accumulate(counts))
422422
if len(cum_counts) != n:
423423
raise ValueError('The number of counts does not match the population')
424-
total = cum_counts.pop()
424+
total = cum_counts.pop() if cum_counts else 0
425425
if not isinstance(total, int):
426426
raise TypeError('Counts must be integers')
427-
if total <= 0:
428-
raise ValueError('Total of counts must be greater than zero')
427+
if total < 0:
428+
raise ValueError('Counts must be non-negative')
429429
selections = self.sample(range(total), k=k)
430430
bisect = _bisect
431431
return [population[bisect(cum_counts, s)] for s in selections]

Lib/test/test_random.py

+14-2
Original file line numberDiff line numberDiff line change
@@ -225,15 +225,27 @@ def test_sample_with_counts(self):
225225
sample(['red', 'green', 'blue'], counts=10, k=10) # counts not iterable
226226
with self.assertRaises(ValueError):
227227
sample(['red', 'green', 'blue'], counts=[-3, -7, -8], k=2) # counts are negative
228-
with self.assertRaises(ValueError):
229-
sample(['red', 'green', 'blue'], counts=[0, 0, 0], k=2) # counts are zero
230228
with self.assertRaises(ValueError):
231229
sample(['red', 'green'], counts=[10, 10], k=21) # population too small
232230
with self.assertRaises(ValueError):
233231
sample(['red', 'green', 'blue'], counts=[1, 2], k=2) # too few counts
234232
with self.assertRaises(ValueError):
235233
sample(['red', 'green', 'blue'], counts=[1, 2, 3, 4], k=2) # too many counts
236234

235+
# Cases with zero counts match equivalents without counts (see gh-130285)
236+
self.assertEqual(
237+
sample('abc', k=0, counts=[0, 0, 0]),
238+
sample([], k=0),
239+
)
240+
self.assertEqual(
241+
sample([], 0, counts=[]),
242+
sample([], 0),
243+
)
244+
with self.assertRaises(ValueError):
245+
sample([], 1, counts=[])
246+
with self.assertRaises(ValueError):
247+
sample('x', 1, counts=[0])
248+
237249
def test_choices(self):
238250
choices = self.gen.choices
239251
data = ['red', 'green', 'blue', 'yellow']
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
Fix corner case for :func:`random.sample` allowing the *counts* parameter to
2+
specify an empty population. So now, ``sample([], 0, counts=[])`` and
3+
``sample('abc', k=0, counts=[0, 0, 0])`` both give the same result as
4+
``sample([], 0)``.

0 commit comments

Comments
 (0)