mirror of
https://github.com/python/cpython.git
synced 2025-08-04 08:59:19 +00:00
[3.13] gh-130285: Fix handling of zero or empty counts in random.sample() (gh-130291) (gh-130416)
This commit is contained in:
parent
3d88c18303
commit
8ef89474b9
3 changed files with 21 additions and 5 deletions
|
@ -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]
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue