implement random selection in Python
Paul Rubin
http
Fri Nov 16 06:30:06 EST 2007
Bruza <benruza at gmail.com> writes:
> But how about the general case, for N > 1 and N < len(items)? Is there
> some clever algorithm using Python standard "random" package
Yeah, I'm not sure what the name for it is, but there'ss a well known
algorithm that's sort of an online verison of random.choice. The
famous N=1 example where all probabilities are equal goes:
# choose a random element of seq
for k,s in enumerate(seq):
if random() < 1.0/(k+1):
choice = s
you should be able to generalize this to N items with different
probabilities.
More information about the Python-list
mailing list