random.SystemRandom().randint() inefficient

Roel Schroeven roel at roelschroeven.net
Wed Jul 27 14:44:45 EDT 2022


Cecil Westerhof via Python-list schreef op 27/07/2022 om 17:43:
> "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)]
Do you know in advance how many items you'll need, or maybe an upper 
limit on the amount? In that case it might be more efficient to use 
random.sample(to_try, k=nr_items_needed).

-- 
"Honest criticism is hard to take, particularly from a relative, a friend,
an acquaintance, or a stranger."
         -- Franklin P. Jones



More information about the Python-list mailing list