[Tutor] Weighted randomness & probability, was: (No Subject)

kevin parks kp87@lycos.com
Sat, 23 Feb 2002 18:32:35 +0900


Scott Widney,

Thanks for taking the time to reply. I am starting to get a glimpse of what this does now. Your approach below is a sort of 'plug-in' approach, where the user passes in the list and the function random.random(). I suppose one could pass in other functions but i am not sure that in this context it makes much sense to do so. Since that would defeat the purpose of the weights... 

I'll try running this when i get connected to the net again (no interpreter here). It will be fun to try to compair this engine with the one in Paul's WeightedList class.

Thanks,

kevin





>###
>def weightedPick(weightedList, choice):
>	""" weightedList is of the form: [('symbol', weight), ...]
>	    where 0.0 < weight < 1.0
>	"""
>	if len(weightedList) == 1:
>		return weightedList[0][0]
>	if choice < weightedList[0][1]:
>		return weightedList[0][0]
>	else:
>		return weightedPick(weightedList[1:],
>                                (choice - weightedList[0][1]))
>###
>Some notes:
>The function doesn't check to see if the sum of the weights =~ 1.0 (why
>would you want anything else?). A Class that wraps the function and the data
>could do that. For that matter, the function doesn't ensure that 'choice' is
>between 0.0 and 1.0; but that's what random.random() returns. Again, I
>suppose that's a job for the Class.
>
>One other thing: I haven't had the chance to run this 1000 or so times to
>check its accuracy. Does anyone have the time?