]> granicus.if.org Git - python/commitdiff
SF bug #1460340: random.sample can raise KeyError
authorRaymond Hettinger <python@rcn.com>
Wed, 29 Mar 2006 09:13:13 +0000 (09:13 +0000)
committerRaymond Hettinger <python@rcn.com>
Wed, 29 Mar 2006 09:13:13 +0000 (09:13 +0000)
Fix the hit and miss style of testing for sets and dicts.

Lib/random.py
Lib/test/test_random.py

index b4ad2b38ae9af42aa11dfd9410f434b430e210f1..943fa51a88a2a9b024211db7b3df5b745707ad97 100644 (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  -------------------
index 9c2e0d0d86dac5ec7dfbba831624b3ebb12eb23a..c9431b372647dcf16474119e01705d1549192e3c 100644 (file)
@@ -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