fastest method to choose a random element

bukzor workitharder at gmail.com
Sat Jan 5 16:35:08 EST 2008


On Jan 5, 8:14 am, c... at mailinator.com wrote:
> On Jan 5, 5:07 pm, c... at mailinator.com wrote:
>
> > Hello, Paul and Arnaud.
> > While I think about your answers: do you think there is any way to
> > avoid shuffle?
> > It may take unnecessary long on a long list most of whose elements
> > have the property.
>
> Umm...
> You provide nice answers in the case many elements are picked from the
> same list.
> Any ideas for the case when the picker is called many times on a
> program, but never twice with the same list?


Here's my stab:

from random import randint, seed
from time import time
from sys import stdout
seed(time())

iterations = 0#DEBUG
def pick_random(seq, prop=bool):
    temp = list(seq)
    global iterations#DEBUG
    while temp:
        iterations += 1#DEBUG
        i = randint(0, len(temp) - 1)
        if prop(temp[i]): return temp[i]
        else: del temp[i]


def generate_list(length):
    l = list()
    for x in xrange(length): l.append(randint(0,1) * randint(1,1000))
    return l

count = 0
for x in xrange(1000):
    count += 1
    print pick_random(generate_list(1000)),

print
print "AVERAGE ITERATIONS:", float(iterations) / count




The average number of iterations is 1/p where p is the chance of your
property being true. It's independent of list size! Just remove the
DEBUG lines and it's ready for use.

--Buck



More information about the Python-list mailing list