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

This commit is contained in:
Raymond Hettinger 2018-07-04 15:28:20 -07:00 committed by GitHub
parent bd81cbd584
commit e69cd169af
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
1 changed files with 4 additions and 4 deletions

View File

@ -371,19 +371,19 @@ class Random(_random.Random):
""" """
random = self.random random = self.random
n = len(population)
if cum_weights is None: if cum_weights is None:
if weights is None: if weights is None:
_int = int _int = int
total = len(population) return [population[_int(random() * n)] for i in range(k)]
return [population[_int(random() * total)] for i in range(k)]
cum_weights = list(_itertools.accumulate(weights)) cum_weights = list(_itertools.accumulate(weights))
elif weights is not None: elif weights is not None:
raise TypeError('Cannot specify both weights and cumulative weights') 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') raise ValueError('The number of weights does not match the population')
bisect = _bisect.bisect bisect = _bisect.bisect
total = cum_weights[-1] total = cum_weights[-1]
hi = len(cum_weights) - 1 hi = n - 1
return [population[bisect(cum_weights, random() * total, 0, hi)] return [population[bisect(cum_weights, random() * total, 0, hi)]
for i in range(k)] for i in range(k)]