implement random selection in Python
Scott David Daniels
Scott.Daniels at Acm.Org
Mon Nov 19 22:25:27 EST 2007
J. Clifford Dyer wrote:
> My understanding of what you are looking for is that on each individual selection,
> the probability of picking a given name is that name's prob value, divided by the
> sum of all prob values. That is, in the following case:
> items = [('Mary', 96),('Shimon', 1), ('Aisha', 1), ('Toshiro', 2)]
> ... On the first pass Mary has a 96% chance of getting selected, ....
> If that is correct, then the following might meet your needs:
>
> from random import choice
>
> def select(weighted_list, n=1):
> selected = set()
> for iteration in xrange(n):
> print iteration
> selection_list = []
> for item in weighted_list:
> if item[0] not in selected:
> selection_list.extend([item[0]] * item[1])
> #print selection_list
> this_choice = choice(selection_list)
> #print this_choice
> selected.add(this_choice)
> return selected
or even:
def picks(weighted_list, N):
result = []
adict = dict(weighted_list)
total = sum(adict.values())
for i in range(N):
score = random.random() * total
for choice, weight in cp.iteritems():
if weight < score:
score -= weight
else:
result.append(choice)
total -= cp.pop(choice)
break
else:
raise ValueError('ran out of data')
return result
-Scott
More information about the Python-list
mailing list