summaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorRaymond Hettinger <python@rcn.com>2016-10-29 23:55:36 (GMT)
committerRaymond Hettinger <python@rcn.com>2016-10-29 23:55:36 (GMT)
commit30d00e54dde47b11f5b338aaba17760b641e1705 (patch)
tree4d185bcc465b08f57558d1b8b39f788efba2fc82
parentab5cf4da4e57fd317e6c4baaaa1d679c0ee9ef08 (diff)
downloadcpython-30d00e54dde47b11f5b338aaba17760b641e1705.zip
cpython-30d00e54dde47b11f5b338aaba17760b641e1705.tar.gz
cpython-30d00e54dde47b11f5b338aaba17760b641e1705.tar.bz2
Issue #18844: Make the various ways for specifing weights produce the same results.
-rw-r--r--Lib/random.py7
-rw-r--r--Lib/test/test_random.py16
-rw-r--r--Misc/NEWS3
3 files changed, 23 insertions, 3 deletions
diff --git a/Lib/random.py b/Lib/random.py
index ef8cb05..a047444 100644
--- a/Lib/random.py
+++ b/Lib/random.py
@@ -344,10 +344,12 @@ class Random(_random.Random):
the selections are made with equal probability.
"""
+ random = self.random
if cum_weights is None:
if weights is None:
- choice = self.choice
- return [choice(population) for i in range(k)]
+ _int = int
+ total = len(population)
+ return [population[_int(random() * total)] for i in range(k)]
else:
cum_weights = list(_itertools.accumulate(weights))
elif weights is not None:
@@ -355,7 +357,6 @@ class Random(_random.Random):
if len(cum_weights) != len(population):
raise ValueError('The number of weights does not match the population')
bisect = _bisect.bisect
- random = self.random
total = cum_weights[-1]
return [population[bisect(cum_weights, random() * total)] for i in range(k)]
diff --git a/Lib/test/test_random.py b/Lib/test/test_random.py
index 4d5a874..dd27152 100644
--- a/Lib/test/test_random.py
+++ b/Lib/test/test_random.py
@@ -629,6 +629,22 @@ class MersenneTwister_TestBasicOps(TestBasicOps, unittest.TestCase):
self.assertTrue(stop < x <= start)
self.assertEqual((x+stop)%step, 0)
+ def test_choices_algorithms(self):
+ # The various ways of specifing weights should produce the same results
+ choices = self.gen.choices
+ n = 13132817
+
+ self.gen.seed(8675309)
+ a = self.gen.choices(range(n), k=10000)
+
+ self.gen.seed(8675309)
+ b = self.gen.choices(range(n), [1]*n, k=10000)
+ self.assertEqual(a, b)
+
+ self.gen.seed(8675309)
+ c = self.gen.choices(range(n), cum_weights=range(1, n+1), k=10000)
+ self.assertEqual(a, c)
+
def gamma(z, sqrt2pi=(2.0*pi)**0.5):
# Reflection to right half of complex plane
if z < 0.5:
diff --git a/Misc/NEWS b/Misc/NEWS
index 75f0ba6..d49162b 100644
--- a/Misc/NEWS
+++ b/Misc/NEWS
@@ -34,6 +34,9 @@ Library
- Issue #27275: Fixed implementation of pop() and popitem() methods in
subclasses of accelerated OrderedDict.
+- Issue #18844: The various ways of specifing weights for random.choices()
+ now produce the same result sequences.
+
- Issue #28255: calendar.TextCalendar().prmonth() no longer prints a space
at the start of new line after printing a month's calendar. Patch by
Xiang Zhang.