Created
October 15, 2020 23:33
-
-
Save netEmmanuel/60ea05d6ab310e8bb51dc15beea63762 to your computer and use it in GitHub Desktop.
Coin Flip game between two friends: You and your friend toss a coin continuously, if the sequence HH appears first you win, if TH appears first your friend wins, who is more likely to win?
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import random | |
def coin_toss(): | |
friendA = 0 | |
friendB = 0 | |
previousFlip = 0 | |
#continue the loop until one of the friends win | |
while friendA == 0 & friendB == 0: | |
#Head = 1; Tail = 2 | |
coin = random.randint(1, 2) | |
# there must be at least a coin flip before we can start | |
if previousFlip != 0: | |
#A tail and a head in a row | |
if previousFlip == 2 and coin == 1: | |
friendA =1 | |
#Two heads in a row | |
elif previousFlip == 1 and coin == 1: | |
friendB =1 | |
#Take the latest coin flip result as previous coin flip result in the next toss | |
previousFlip = coin | |
# create a dictionary to map friend variable to value | |
var = {friendA:"friendA",friendB:"friendB"} | |
#return winner | |
return var.get(max(var)) | |
count = 0 | |
friend_A_wins = 0 | |
friend_B_wins = 0 | |
#simulate game for 100 times | |
while count < 100: | |
result = coin_toss() | |
if result == "friendA": | |
friend_A_wins +=1 | |
elif result == "friendB": | |
friend_B_wins +=1 | |
count +=1 | |
print ("Friend A wins : ", friend_A_wins ,"times") | |
print ("Friend B wins : ", friend_B_wins ,"times") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment