mirror of
https://github.com/python/cpython.git
synced 2025-08-04 00:48:58 +00:00
SF bug #801342: Bug (documentation or real, your choice) in random.sample.
random.sample() uses one of two algorithms depending on the ratio of the sample size to the population size. One of the algorithms accepted any iterable population argument so long as it defined __len__(). The other had a stronger requirement that the population argument be indexable. While it met the documentation specifications which insisted that the population argument be a sequence, it made random.sample() less usable with sets. So, the second algorithm was modified to coerce non-indexable iterables and dictionaries into a tuple before proceeding.
This commit is contained in:
parent
c8b08b446a
commit
66d09f1b30
2 changed files with 14 additions and 0 deletions
|
@ -258,6 +258,10 @@ class Random(_random.Random):
|
|||
result[i] = pool[j]
|
||||
pool[j] = pool[n-i-1] # move non-selected item into vacancy
|
||||
else:
|
||||
try:
|
||||
n > 0 and (population[0], population[n//2], population[n-1])
|
||||
except (TypeError, KeyError): # handle sets and dictionaries
|
||||
population = tuple(population)
|
||||
selected = {}
|
||||
for i in xrange(k):
|
||||
j = _int(random() * n)
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue