[Tutor] Weighted Random Choice - Anyone have an efficient algorithm?

Dave Angel davea at ieee.org
Fri Dec 24 13:55:46 CET 2010


On 01/-10/-28163 02:59 PM, Albert-Jan Roskam wrote:
> Hi Steven,
>
> Doesn't this qualify as 'monkeying with the loop index'? [*]
>
>>>> import random
>>>> weights = [5, 20, 75]
>>>> counts = {0:0, 1:0, 2:0}
>>>> for i in xrange(1000000):
> ...     i = weighted_choice(weights) #<--- monkeying right here (?)
> ...     counts[i] += 1
>
> [*] http://stackoverflow.com/questions/457036/dont-monkey-with-the-loop-index
>
(please don't top-post in these forums)

Your citation is for C#, where the loop index does indeed get changed. 
In Python a loop protects itself against such monkeying, so the example 
still executes a million times.

It still would be better to use a different temp variable for clarity, 
but it's not as important as in other languages.

DaveA


More information about the Tutor mailing list