[Python-checkins] Convert range to repeat for choices() (#11889)

Raymond Hettinger webhook-mailer at python.org
Sat Feb 16 16:30:55 EST 2019


https://github.com/python/cpython/commit/5382203ae1bf637f9554277d5597d04805934420
commit: 5382203ae1bf637f9554277d5597d04805934420
branch: master
author: Raymond Hettinger <rhettinger at users.noreply.github.com>
committer: GitHub <noreply at github.com>
date: 2019-02-16T13:30:51-08:00
summary:

Convert range to repeat for choices() (#11889)

files:
M Lib/random.py

diff --git a/Lib/random.py b/Lib/random.py
index 754b2952a0f7..79ef30d7d18d 100644
--- a/Lib/random.py
+++ b/Lib/random.py
@@ -43,7 +43,7 @@
 from os import urandom as _urandom
 from _collections_abc import Set as _Set, Sequence as _Sequence
 from hashlib import sha512 as _sha512
-from itertools import accumulate as _accumulate
+from itertools import accumulate as _accumulate, repeat as _repeat
 from bisect import bisect as _bisect
 import os as _os
 
@@ -389,7 +389,7 @@ def choices(self, population, weights=None, *, cum_weights=None, k=1):
             if weights is None:
                 _int = int
                 n += 0.0    # convert to float for a small speed improvement
-                return [population[_int(random() * n)] for i in range(k)]
+                return [population[_int(random() * n)] for i in _repeat(None, k)]
             cum_weights = list(_accumulate(weights))
         elif weights is not None:
             raise TypeError('Cannot specify both weights and cumulative weights')
@@ -399,7 +399,7 @@ def choices(self, population, weights=None, *, cum_weights=None, k=1):
         total = cum_weights[-1] + 0.0   # convert to float
         hi = n - 1
         return [population[bisect(cum_weights, random() * total, 0, hi)]
-                for i in range(k)]
+                for i in _repeat(None, k)]
 
 ## -------------------- real-valued distributions  -------------------
 



More information about the Python-checkins mailing list