[Python-checkins] cpython (merge 3.6 -> default): merge
raymond.hettinger
python-checkins at python.org
Sat Oct 29 19:57:15 EDT 2016
https://hg.python.org/cpython/rev/02c620e7a44d
changeset: 104807:02c620e7a44d
parent: 104805:fe842efbe1ed
parent: 104806:32bfc81111b6
user: Raymond Hettinger <python at rcn.com>
date: Sat Oct 29 16:57:09 2016 -0700
summary:
merge
files:
Lib/random.py | 7 ++++---
Lib/test/test_random.py | 16 ++++++++++++++++
2 files changed, 20 insertions(+), 3 deletions(-)
diff --git a/Lib/random.py b/Lib/random.py
--- a/Lib/random.py
+++ b/Lib/random.py
@@ -344,10 +344,12 @@
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 @@
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
--- a/Lib/test/test_random.py
+++ b/Lib/test/test_random.py
@@ -625,6 +625,22 @@
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:
--
Repository URL: https://hg.python.org/cpython
More information about the Python-checkins
mailing list