0

I am trying to write a code to simulate coin toss where each toss game ends when two consecutive results acquired. For example (H,H) game ends at two tosses (T,H,T,T) game ends at 4 tosses. I managed to write a code to simulate it but I am unable to get the result such as how many game ended in how many tosses. Can somebody help on that issue?

import random

def cointoss():
    return random.choice(["Heads", "Tails"])

def play_fair_game():
    tosses = []
    tosses.append(cointoss())
    tosses.append(cointoss())

    # if already not, toss a coin until the last 2 tosses are same, 
    while tosses[-1] != tosses[-2]:
        tosses.append(cointoss())
    return tosses


if __name__ == '__main__':
    game_results = []

    for i in range(0, 10000):
        game_result = play_fair_game()
        print(f"Game ended at {len(game_result)} toss. The tosses are: {game_result}")

        # For later analysis, store the results in an array
        game_results.append(game_result)
        
thefourtheye
  • 233,700
  • 52
  • 457
  • 497

2 Answers2

0

If I understand correctly, you want to print how many games ended in 2 tosses, how many games ended in 3 tosses etc.

Your list games_results already include the results of the games. First let's create a list of of many tosses it took for each game:

game_results_count = [len(x) for x in game_results]

Then the problem is "how to count the number of occurrences of each number in a list"? (how many 1 appears, how many 2, etc.) for this you can Counter:

from collections import Counter
print(Counter(game_results_count))

It will create a dictionary with value (aka how many tosses) as key and amount of games as values. If no game ended in 5 tosses for example, it will not be a value in the dictionary. You can add it artificially afterwards if you want zeros as well.

This will do the trick. See more here: How do I count the occurrences of a list item?

Roim
  • 2,986
  • 2
  • 10
  • 25
0

You can use a Counter for that.

from collections import Counter

...

if __name__ == '__main__':
    game_results = Counter() #Use a Counter instead of a list

    for i in range(0, 10000):
        game_result = play_fair_game()
        num_tosses = len(game_result) #count tosses
        print(f"Game ended at {num_tosses} toss. The tosses are: {game_result}")

        # For later analysis, store the results in an array
        game_results.update({num_tosses}) #update the Counter
    print(game_results) #num_tosses:how_many_games_ended_with_that_many_tosses
    #Counter({2: 5011, 3: 2459, 4: 1254, 5: 664, 6: 307, 7: 143, 8: 83, 9: 37, 10: 23, 11: 9, 13: 5, 12: 3, 14: 2})
alec_djinn
  • 10,104
  • 8
  • 46
  • 71