diff options
author | Raymond Hettinger <rhettinger@users.noreply.github.com> | 2018-07-04 22:28:20 (GMT) |
---|---|---|
committer | GitHub <noreply@github.com> | 2018-07-04 22:28:20 (GMT) |
commit | e69cd169afdfb013db9e8dbfd0f87f7658660f32 (patch) | |
tree | 974ede8325635b8051b44b7e4960fd257bcc7ac7 | |
parent | bd81cbd584e89ffcf4751e83be9c7cac369206bd (diff) | |
download | cpython-e69cd169afdfb013db9e8dbfd0f87f7658660f32.zip cpython-e69cd169afdfb013db9e8dbfd0f87f7658660f32.tar.gz cpython-e69cd169afdfb013db9e8dbfd0f87f7658660f32.tar.bz2 |
Minor code refactoring. Compute len() one fewer times on one code path. (GH-8094)
-rw-r--r-- | Lib/random.py | 8 |
1 files changed, 4 insertions, 4 deletions
diff --git a/Lib/random.py b/Lib/random.py index 1006908..b2c0d6f 100644 --- a/Lib/random.py +++ b/Lib/random.py @@ -371,19 +371,19 @@ class Random(_random.Random): """ 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)] |