fastest method to choose a random element
bukzor
workitharder at gmail.com
Sat Jan 5 16:45:16 EST 2008
On Jan 5, 9:12 am, "Martin v. Löwis" <mar... at v.loewis.de> wrote:
> > Any other ideas?
>
> How about this:
>
> def random_pick(list, property):
> L = len(list)
> pos = start = random.randrange(L)
> while 1:
> x = list[pos]
> if property(x): return x
> pos = (pos + 1) % L
> if pos == start:
> raise ValueError, "no such item"
>
> Regards,
> Martin
I thought about this, but in the sequence "00012" (and property =
bool) the 1 will be returned four times as often as the 2. Maybe
that's ok...
More information about the Python-list
mailing list