[3.12] gh-130285: Fix handling of zero or empty counts in random.sample() (gh-130291) (gh-130417)

This commit is contained in:
Miss Islington (bot) 2025-02-21 18:48:46 +01:00 committed by GitHub
parent 91e5e246b3
commit 8db2fa2575
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
3 changed files with 21 additions and 5 deletions

View file

@ -417,11 +417,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]