reuse generators

Posted by wiso on Stack Overflow See other posts from Stack Overflow or by wiso
Published on 2010-04-17T22:41:36Z Indexed on 2010/04/17 22:43 UTC
Read the original article Hit count: 125

Filed under:
|
|

I need to check the central limit with dices. Rool D dices. Sum the results. Repeat the same thing for N times. Change D and repeat.

There's no need to store random values so I want to use only generators. The problem is that generators are consuming, I can't resuging them more times. Now my code use explicit for and I don't like it.

dice_numbers = (1, 2, 10, 100, 1000)
repetitions = 10000
for dice_number in dice_numbers: # how many dice to sum
    sum_container = []
    for r in range(repetitions):
        rool_sum = sum((random.randint(1,6) for _ in range(dice_number)))
        sum_container.append(rool_sum)
        plot_histogram(sum_container)

I want to create something like

for r in repetitions:
    rools_generator = (random.randint(1,6) for _ in range(dice_number)
    sum_generator = (sum(rools_generator) for _ in range(r))

but the second time I resuse rools_generator it is condumed. I need to construct generator class?

© Stack Overflow or respective owner

Related posts about python

Related posts about generator