diff options
author | Raymond Hettinger <python@rcn.com> | 2006-03-29 09:13:13 (GMT) |
---|---|---|
committer | Raymond Hettinger <python@rcn.com> | 2006-03-29 09:13:13 (GMT) |
commit | 3c3346daa9bf900080428ed12b6d83aa04f7332b (patch) | |
tree | 08c345b00a41ebb40ee9bf4ade8cc3833cc7ba57 | |
parent | 62e97f023bf0c02f5f3c1a1552e8136c0b5c4cff (diff) | |
download | cpython-3c3346daa9bf900080428ed12b6d83aa04f7332b.zip cpython-3c3346daa9bf900080428ed12b6d83aa04f7332b.tar.gz cpython-3c3346daa9bf900080428ed12b6d83aa04f7332b.tar.bz2 |
SF bug #1460340: random.sample can raise KeyError
Fix the hit and miss style of testing for sets and dicts.
-rw-r--r-- | Lib/random.py | 21 | ||||
-rw-r--r-- | Lib/test/test_random.py | 3 |
2 files changed, 14 insertions, 10 deletions
diff --git a/Lib/random.py b/Lib/random.py index b4ad2b3..943fa51 100644 --- a/Lib/random.py +++ b/Lib/random.py @@ -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 ------------------- diff --git a/Lib/test/test_random.py b/Lib/test/test_random.py index 9c2e0d0..c9431b3 100644 --- a/Lib/test/test_random.py +++ b/Lib/test/test_random.py @@ -96,6 +96,9 @@ class TestBasicOps(unittest.TestCase): self.gen.sample(dict.fromkeys('abcdefghijklmnopqrst'), 2) self.gen.sample(str('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): # Ensure that the seed() method initializes all the hidden state. In |