mirror of
https://github.com/python/cpython.git
synced 2025-08-01 15:43:13 +00:00
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:
parent
62e97f023b
commit
3c3346daa9
2 changed files with 14 additions and 10 deletions
|
@ -312,17 +312,18 @@ class Random(_random.Random):
|
||||||
pool[j] = pool[n-i-1] # move non-selected item into vacancy
|
pool[j] = pool[n-i-1] # move non-selected item into vacancy
|
||||||
else:
|
else:
|
||||||
try:
|
try:
|
||||||
n > 0 and (population[0], population[n//2], population[n-1])
|
selected = set()
|
||||||
except (TypeError, KeyError): # handle non-sequence iterables
|
selected_add = selected.add
|
||||||
population = tuple(population)
|
for i in xrange(k):
|
||||||
selected = set()
|
|
||||||
selected_add = selected.add
|
|
||||||
for i in xrange(k):
|
|
||||||
j = _int(random() * n)
|
|
||||||
while j in selected:
|
|
||||||
j = _int(random() * n)
|
j = _int(random() * n)
|
||||||
selected_add(j)
|
while j in selected:
|
||||||
result[i] = population[j]
|
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
|
return result
|
||||||
|
|
||||||
## -------------------- real-valued distributions -------------------
|
## -------------------- real-valued distributions -------------------
|
||||||
|
|
|
@ -96,6 +96,9 @@ class TestBasicOps(unittest.TestCase):
|
||||||
self.gen.sample(dict.fromkeys('abcdefghijklmnopqrst'), 2)
|
self.gen.sample(dict.fromkeys('abcdefghijklmnopqrst'), 2)
|
||||||
self.gen.sample(str('abcdefghijklmnopqrst'), 2)
|
self.gen.sample(str('abcdefghijklmnopqrst'), 2)
|
||||||
self.gen.sample(tuple('abcdefghijklmnopqrst'), 2)
|
self.gen.sample(tuple('abcdefghijklmnopqrst'), 2)
|
||||||
|
# SF bug #1460340 -- random.sample can raise KeyError
|
||||||
|
a = dict.fromkeys(range(10)+range(10,100,2)+range(100,110))
|
||||||
|
self.gen.sample(a,3)
|
||||||
|
|
||||||
def test_gauss(self):
|
def test_gauss(self):
|
||||||
# Ensure that the seed() method initializes all the hidden state. In
|
# Ensure that the seed() method initializes all the hidden state. In
|
||||||
|
|
Loading…
Add table
Add a link
Reference in a new issue