[Python-checkins] r84581 - in python/branches/py3k/Lib: random.py test/test_random.py

raymond.hettinger python-checkins at python.org
Tue Sep 7 12:06:56 CEST 2010


Author: raymond.hettinger
Date: Tue Sep 7 12:06:56 2010
New Revision: 84581
Log:
Fix corner case for Random.choice() and add tests.
Modified:
 python/branches/py3k/Lib/random.py
 python/branches/py3k/Lib/test/test_random.py
Modified: python/branches/py3k/Lib/random.py
==============================================================================
--- python/branches/py3k/Lib/random.py	(original)
+++ python/branches/py3k/Lib/random.py	Tue Sep 7 12:06:56 2010
@@ -239,7 +239,11 @@
 
 def choice(self, seq):
 """Choose a random element from a non-empty sequence."""
- return seq[self._randbelow(len(seq))] # raises IndexError if seq is empty
+ try:
+ i = self._randbelow(len(seq))
+ except ValueError:
+ raise IndexError('Cannot choose from an empty sequence')
+ return seq[i]
 
 def shuffle(self, x, random=None, int=int):
 """x, random=random.random -> shuffle list x in place; return None.
Modified: python/branches/py3k/Lib/test/test_random.py
==============================================================================
--- python/branches/py3k/Lib/test/test_random.py	(original)
+++ python/branches/py3k/Lib/test/test_random.py	Tue Sep 7 12:06:56 2010
@@ -42,6 +42,13 @@
 self.assertRaises(TypeError, self.gen.seed, 1, 2, 3, 4)
 self.assertRaises(TypeError, type(self.gen), [])
 
+ def test_choice(self):
+ choice = self.gen.choice
+ with self.assertRaises(IndexError):
+ choice([])
+ self.assertEqual(choice([50]), 50)
+ self.assertIn(choice([25, 75]), [25, 75])
+
 def test_sample(self):
 # For the entire allowable range of 0 <= k <= N, validate that
 # the sample is of the correct length and contains only unique items


More information about the Python-checkins mailing list

AltStyle によって変換されたページ (->オリジナル) /