fastest method to choose a random element

Paul Hankin paul.hankin at gmail.com
Sat Jan 5 12:22:29 EST 2008


On Jan 5, 5:12 pm, "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"

This might be acceptable for the OP's use, but it's strongly biased
towards values which follow a long stream of things that fail
property.

print [random_pick(range(100), lambda x:x > 90)
    for i in range(999)].count(91)

929

If it were uniform, it should be around 111.

--
Paul Hankin



More information about the Python-list mailing list