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

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

View file

@ -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]