SF bug #1460340: random.sample can raise KeyError

Fix the hit and miss style of testing for sets and dicts.
This commit is contained in:
Raymond Hettinger 2006-03-29 09:13:13 +00:00
parent 62e97f023b
commit 3c3346daa9
2 changed files with 14 additions and 10 deletions

View file

@ -312,17 +312,18 @@ class Random(_random.Random):
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 non-sequence iterables
population = tuple(population)
selected = set()
selected_add = selected.add
for i in xrange(k):
j = _int(random() * n)
while j in selected:
selected = set()
selected_add = selected.add
for i in xrange(k):
j = _int(random() * n)
selected_add(j)
result[i] = population[j]
while j in selected:
j = _int(random() * n)
selected_add(j)
result[i] = population[j]
except (TypeError, KeyError): # handle sets and dictionaries
if isinstance(population, list):
raise
return self.sample(list(population), k)
return result
## -------------------- real-valued distributions -------------------