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