Improve the error message for choices(population, 10) (GH-25267) (GH-25477)

This commit is contained in:
Miss Islington (bot) 2021-04-19 23:15:50 -07:00 committed by GitHub
parent 072ec69af5
commit fa03efda3d
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
1 changed files with 9 additions and 1 deletions

View File

@ -485,7 +485,15 @@ def choices(self, population, weights=None, *, cum_weights=None, k=1):
floor = _floor floor = _floor
n += 0.0 # convert to float for a small speed improvement n += 0.0 # convert to float for a small speed improvement
return [population[floor(random() * n)] for i in _repeat(None, k)] return [population[floor(random() * n)] for i in _repeat(None, k)]
cum_weights = list(_accumulate(weights)) try:
cum_weights = list(_accumulate(weights))
except TypeError:
if not isinstance(weights, int):
raise
k = weights
raise TypeError(
f'The number of choices must be a keyword argument: {k=}'
) from None
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) != n: if len(cum_weights) != n: