Pregunta

Hello I'm trying to make a function including the random module that only accumulates the sum of odd rolls of n-dice, n-sided times. Sounds a little confusing but for example if I rolled 2-sided die 2 times and got 1 and 2, the result would be only 1 (since 2 is even). Here's what I have:

import random

def roll(sides, dice):
    y = 0
    for i in range(1, dice+1):
        if y%2 == 1:
            y = y + random.randrange(1, sides+1)
    return y

How can I get this to work? It never gets past the first if because it starts at y=0

¿Fue útil?

Solución

In your code, the problem is that you add a random number before checking if it's odd or even in your for loop.

I think you're looking for something like this:

def roll(sides, times):
    final_sum = 0
    for i in range(times):
        randnum = random.randrange(sides)
        final_sum += randnum if randnum % 2 else 0
    return final_sum

Otros consejos

Count of odd rolls:

count([1 for i in xrange(num_of_rolls) if (random.randint(1, sides)) % 2])

Sum:

rolls = [random.randint(1, sides) for i in range(num_of_rolls)]
sum_of_odd = sum([roll for foll in rolls if roll % 2])

Not tested, but should work :)

..you wanted the one-liner, this is the oneliner :)

sum(r for r in (random.randrange(1, sides+1) for i in xrange(dice)) if r % 2)

Anyways, to reply to the OP's question: the problem with your code is you're checking whether the sum so far is odd, not the current die roll... to do that, you should do like this:

import random

def roll(sides, dice):
    total = 0
    for i in range(dice):
        result = random.randrange(1, sides+1)
        if result % 2:
            y += result
    return y

Your code should assign the random value to another variable first. Then check if odd. Then add it.

import random

def roll(sides, dice):
    y = 0
    roll = random.randrange(1, sides+1)
    for i in range(1, dice+1):
        if roll%2 == 1:
            y = y + roll
    return y
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top