0

We have a game, the game consists of 500 rounds. In each round, two coins are being rolled at the same time, if both coins have 'heads' then we win £1, if both have 'tails' then we lose £1 and if we have a situation where one coin shows 'heads' and the other coin shows 'tails' or vice versa then we just 'try again'.

coin_one = [random.randint(0, 1) for x in range(500)]
coin_two = [random.randint(0, 1) for x in range(500)]

game = zip(coin_one, coin_two)

for a, b in game:
    if a and b:
        print(1)
    elif not a and not b:
        print(-1)
else:
    print('please try again') # or continue

The results of this are:

1 please try again -1 please try again please try again please try again -1 -1 1 -1 ,............, 1

I am trying to find the sum of the results so that I can know how much the player of the game won or lost after the game is complete (500 rounds).

After obtaining the result (total amount won/lost) of playing just one game (500 rounds), I hope to play the game 100 times to create some summary statistics like mean, max, min and standard deviation of playing this game.

Moses Koledoye
  • 77,341
  • 8
  • 133
  • 139
  • instead of printing 1 and -1 you can have a variable `sum = 0` before the `for` loop and add these values to the sum variable. At the end of the loop you'll get the total amount won/lost – S Raghav Feb 04 '17 at 13:28

2 Answers2

2

You can simply accumulate the sum of the values into a new variable:

total = 0
for a, b in game:
    if a and b:
        total += 1
    elif not a and not b:
        total -= 1
    else:
        print('please try again')

print(total)

And if you don't want to print anything in the case both of them have mismatching values, you can do a one-liner:

s = sum(0 if a^b else (-1, 1)[a and b] for a, b in game)

Note that ^ is the xor operator, which returns a falsy value if both operands are the same. Put that in a ternary and we can select -1 or 1 by indexing with the result from shortcuiting with and both operands.

Moses Koledoye
  • 77,341
  • 8
  • 133
  • 139
0

As others suggested, the total is what you look like to be searching for. Define it before the loop, then it gets in/decremented within the loop.

total = 0
for a, b in game:
    if a and b:
        total += 1
    elif not a and not b:
        total -= 1
Eduardo
  • 4,282
  • 2
  • 49
  • 63