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)
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_resultsalready 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:
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?