mirror of
https://github.com/python/cpython.git
synced 2025-09-19 15:10:58 +00:00
merge
This commit is contained in:
commit
ba25f61490
2 changed files with 20 additions and 3 deletions
|
@ -344,10 +344,12 @@ class Random(_random.Random):
|
||||||
the selections are made with equal probability.
|
the selections are made with equal probability.
|
||||||
|
|
||||||
"""
|
"""
|
||||||
|
random = self.random
|
||||||
if cum_weights is None:
|
if cum_weights is None:
|
||||||
if weights is None:
|
if weights is None:
|
||||||
choice = self.choice
|
_int = int
|
||||||
return [choice(population) for i in range(k)]
|
total = len(population)
|
||||||
|
return [population[_int(random() * total)] for i in range(k)]
|
||||||
else:
|
else:
|
||||||
cum_weights = list(_itertools.accumulate(weights))
|
cum_weights = list(_itertools.accumulate(weights))
|
||||||
elif weights is not None:
|
elif weights is not None:
|
||||||
|
@ -355,7 +357,6 @@ class Random(_random.Random):
|
||||||
if len(cum_weights) != len(population):
|
if len(cum_weights) != len(population):
|
||||||
raise ValueError('The number of weights does not match the population')
|
raise ValueError('The number of weights does not match the population')
|
||||||
bisect = _bisect.bisect
|
bisect = _bisect.bisect
|
||||||
random = self.random
|
|
||||||
total = cum_weights[-1]
|
total = cum_weights[-1]
|
||||||
return [population[bisect(cum_weights, random() * total)] for i in range(k)]
|
return [population[bisect(cum_weights, random() * total)] for i in range(k)]
|
||||||
|
|
||||||
|
|
|
@ -625,6 +625,22 @@ class MersenneTwister_TestBasicOps(TestBasicOps, unittest.TestCase):
|
||||||
self.assertTrue(stop < x <= start)
|
self.assertTrue(stop < x <= start)
|
||||||
self.assertEqual((x+stop)%step, 0)
|
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):
|
def gamma(z, sqrt2pi=(2.0*pi)**0.5):
|
||||||
# Reflection to right half of complex plane
|
# Reflection to right half of complex plane
|
||||||
if z < 0.5:
|
if z < 0.5:
|
||||||
|
|
Loading…
Add table
Add a link
Reference in a new issue