random.SystemRandom().randint() inefficient
Cecil Westerhof
Cecil at decebal.nl
Wed Jul 27 11:43:27 EDT 2022
"Michael F. Stemper" <michael.stemper at gmail.com> writes:
> This is orthogonal to your question, but might be of some use to you:
>
> The combination of using len(to_try) as an argument to randint() and
> saving the output to a variable named "index" suggests that you might
> be setting up to select a random element from to_try, as in:
> something = to_try[index]
>
> If that is the case, you might want to consider using random.choice() instead:
>
> >>> from random import choice
> >>> to_try = [2,3,5,7,11,13,"seventeen",19]
> >>> choice(to_try)
> 2
> >>> choice(to_try)
> 'seventeen'
> >>> choice(to_try)
> 13
> >>> choice(to_try)
> 5
> >>>
Yes, I try to select a random element, but it has also to be removed,
because an element should not be used more as once.
This is the code I use:
# index = randbelow(len(to_try))
index = randrange(len(to_try))
found = permutation[to_try.pop(index)]
--
Cecil Westerhof
Senior Software Engineer
LinkedIn: http://www.linkedin.com/in/cecilwesterhof
More information about the Python-list
mailing list