[Python-checkins] Minor code refactoring. Compute len() one fewer times on one code path. (GH-8094)

Raymond Hettinger webhook-mailer at python.org
Wed Jul 4 18:28:23 EDT 2018


https://github.com/python/cpython/commit/e69cd169afdfb013db9e8dbfd0f87f7658660f32
commit: e69cd169afdfb013db9e8dbfd0f87f7658660f32
branch: master
author: Raymond Hettinger <rhettinger at users.noreply.github.com>
committer: GitHub <noreply at github.com>
date: 2018-07-04T15:28:20-07:00
summary:

Minor code refactoring.  Compute len() one fewer times on one code path. (GH-8094)

files:
M Lib/random.py

diff --git a/Lib/random.py b/Lib/random.py
index 10069084916f..b2c0d6fcc3b8 100644
--- a/Lib/random.py
+++ b/Lib/random.py
@@ -371,19 +371,19 @@ def choices(self, population, weights=None, *, cum_weights=None, k=1):
 
         """
         random = self.random
+        n = len(population)
         if cum_weights is None:
             if weights is None:
                 _int = int
-                total = len(population)
-                return [population[_int(random() * total)] for i in range(k)]
+                return [population[_int(random() * n)] for i in range(k)]
             cum_weights = list(_itertools.accumulate(weights))
         elif weights is not None:
             raise TypeError('Cannot specify both weights and cumulative weights')
-        if len(cum_weights) != len(population):
+        if len(cum_weights) != n:
             raise ValueError('The number of weights does not match the population')
         bisect = _bisect.bisect
         total = cum_weights[-1]
-        hi = len(cum_weights) - 1
+        hi = n - 1
         return [population[bisect(cum_weights, random() * total, 0, hi)]
                 for i in range(k)]
 



More information about the Python-checkins mailing list