[Tutor] Weighted Random Choice - Anyone have an efficientalgorithm?
Alan Gauld
alan.gauld at btinternet.com
Fri Dec 24 18:57:33 CET 2010
"Albert-Jan Roskam" <fomcl at yahoo.com> wrote
> 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
Not really because the for loop value is not being used as an index.
It could just as well have been written:
>>>> for n in xrange(1000000):
> ... i = weighted_choice(weights) # <--- monkeying right here (?)
> ... counts[i] += 1
The n is not used except to ensure there are a million iterations.
So reusing the name inside the loop body doesn't have any
bad effects. But keeping to a separate name might have been
slightly more readable.
HTH,
--
Alan Gauld
Author of the Learn to Program web site
http://www.alan-g.me.uk/
More information about the Tutor
mailing list