[Python-checkins] r43420 - in python/branches/release24-maint/Lib: random.py test/test_random.py

raymond.hettinger python-checkins at python.org
Wed Mar 29 10:54:56 CEST 2006


Author: raymond.hettinger
Date: Wed Mar 29 10:54:54 2006
New Revision: 43420

Modified:
   python/branches/release24-maint/Lib/random.py
   python/branches/release24-maint/Lib/test/test_random.py
Log:
SF bug #1460340:  random.sample can raise KeyError

Fix the hit and miss style of testing for sets and dicts.



Modified: python/branches/release24-maint/Lib/random.py
==============================================================================
--- python/branches/release24-maint/Lib/random.py	(original)
+++ python/branches/release24-maint/Lib/random.py	Wed Mar 29 10:54:54 2006
@@ -310,15 +310,16 @@
                 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)
-                while j in selected:
+                selected = {}
+                for i in xrange(k):
                     j = _int(random() * n)
-                result[i] = selected[j] = population[j]
+                    while j in selected:
+                        j = _int(random() * n)
+                    result[i] = selected[j] = 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  -------------------

Modified: python/branches/release24-maint/Lib/test/test_random.py
==============================================================================
--- python/branches/release24-maint/Lib/test/test_random.py	(original)
+++ python/branches/release24-maint/Lib/test/test_random.py	Wed Mar 29 10:54:54 2006
@@ -96,6 +96,9 @@
         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


More information about the Python-checkins mailing list