Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit e69cd16

Browse files
authored
Minor code refactoring. Compute len() one fewer times on one code path. (GH-8094)
1 parent bd81cbd commit e69cd16

File tree

1 file changed

+4
-4
lines changed

1 file changed

+4
-4
lines changed

Lib/random.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -371,19 +371,19 @@ def choices(self, population, weights=None, *, cum_weights=None, k=1):
371371
372372
"""
373373
random = self.random
374+
n = len(population)
374375
if cum_weights is None:
375376
if weights is None:
376377
_int = int
377-
total = len(population)
378-
return [population[_int(random() * total)] for i in range(k)]
378+
return [population[_int(random() * n)] for i in range(k)]
379379
cum_weights = list(_itertools.accumulate(weights))
380380
elif weights is not None:
381381
raise TypeError('Cannot specify both weights and cumulative weights')
382-
if len(cum_weights) != len(population):
382+
if len(cum_weights) != n:
383383
raise ValueError('The number of weights does not match the population')
384384
bisect = _bisect.bisect
385385
total = cum_weights[-1]
386-
hi = len(cum_weights) - 1
386+
hi = n - 1
387387
return [population[bisect(cum_weights, random() * total, 0, hi)]
388388
for i in range(k)]
389389

0 commit comments

Comments
 (0)