Created
September 3, 2018 00:52
-
-
Save jmhummel/be4723aaa4a1ba27414b170179db3277 to your computer and use it in GitHub Desktop.
Riddler 2018-08-31 Express, "The New National Pastime: Competitive Coin Flipping"
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 enum(**enums): | |
return type('Enum', (), enums) | |
Coin = enum(HEADS='H', TAILS='T') | |
Team = enum(RED='Red', BLUE='Blue') | |
Goal = enum(RED=[Coin.HEADS, Coin.TAILS], BLUE=[Coin.HEADS, Coin.HEADS]) | |
def flip(): | |
return random.choice([Coin.HEADS, Coin.TAILS]) | |
def play(): | |
winner = None | |
sequence_red = [] | |
sequence_blue = [] | |
while(winner is None): | |
sequence_red.append(flip()) | |
sequence_blue.append(flip()) | |
if (len(sequence_red) >= 2): | |
if (sequence_red[-2:] == Goal.RED): | |
winner = Team.RED | |
if (sequence_blue[-2:] == Goal.BLUE): | |
if winner is Team.RED: | |
winner = None | |
sequence_red = [] | |
sequence_blue = [] | |
else: | |
winner = Team.BLUE | |
return winner | |
def simulate(trials=100): | |
results = {Team.RED:0, Team.BLUE:0} | |
p = 0 | |
for i in xrange(1, trials+1): | |
results[play()] += 1 | |
if (i%(10**p) == 0): | |
print {k:(v*1.0/sum(results.values())) for k,v in results.iteritems()} | |
p += 1 | |
return results | |
print simulate(10000000) | |
""" | |
Output: | |
{'Blue': 0.0, 'Red': 1.0} | |
{'Blue': 0.4, 'Red': 0.6} | |
{'Blue': 0.36, 'Red': 0.64} | |
{'Blue': 0.353, 'Red': 0.647} | |
{'Blue': 0.3672, 'Red': 0.6328} | |
{'Blue': 0.37538, 'Red': 0.62462} | |
{'Blue': 0.376188, 'Red': 0.623812} | |
{'Blue': 0.3752312, 'Red': 0.6247688} | |
{'Blue': 3752312, 'Red': 6247688} | |
""" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment