[Tutor] quickly pulling marbles out of urns
Joel Miller
joel.c.miller at gmail.com
Fri May 16 23:43:19 CEST 2008
I'm looking for a faster way to do the following problem:
I have an urn with many different colors of marbles in it. I pull one
out and note the color. I do not replace it.
For the programming of this, I actually know how many are yellow,
green, etc. So the way the code works right now is:
import math
...
randindex = math.randint(1,number_of_marbles)
for color in colors:
if randindex<=marble_count[color]: #we've found what color it will be
break
else: #try next color
randindex -= marble_count[color]
marble_count[color] -= 1
number_of_marbles -= 1
return color
Unfortunately, I have hundreds of thousands of colors, so it spends a
while on this loop. And I have to keep choosing marbles many times at
different points of the code.
Is there a quicker way to do this?
Thanks,
Joel
More information about the Tutor
mailing list