Skip to content

Instantly share code, notes, and snippets.

@luelista
Created February 26, 2023 15:16
Show Gist options
  • Save luelista/b93683f1cafd55f90a3d327930f126bb to your computer and use it in GitHub Desktop.
Save luelista/b93683f1cafd55f90a3d327930f126bb to your computer and use it in GitHub Desktop.
Monty Hall Problem
#!/usr/bin/env python3
import random
import sys
class GameMasterStrategy:
def step1(self):
self.doors = [1,2,3]
self._correctDoor = random.choice(self.doors)
return self.doors
def step2(self,chosenDoor):
wrongDoors = [door for door in self.doors if door != self._correctDoor]
revealable = [door for door in wrongDoors if door != chosenDoor]
revealedDoor = random.choice(revealable)
remainingDoors = [door for door in self.doors if door != revealedDoor]
return remainingDoors
def step3(self,chosenDoor):
return chosenDoor == self._correctDoor
class Game:
def __init__(self, masterStrategy, playerStrategy):
self.masterStrategy = masterStrategy
self.playerStrategy = playerStrategy
self.wins = 0
self.gamesPlayed = 0
self.stayed = 0
def play(self):
choices = self.masterStrategy.step1()
print("Choices: ", choices)
choice = self.playerStrategy.step1(choices)
print("Player chose ",choice)
remaining_choices = self.masterStrategy.step2(choice)
print("Remaining Choices: ", remaining_choices)
final_choice = self.playerStrategy.step2(remaining_choices)
if final_choice == choice:
print("Player stayed with ",final_choice)
self.stayed += 1
else:
print("Player switched to ", final_choice)
result = self.masterStrategy.step3(final_choice)
self.gamesPlayed += 1
if result:
self.wins += 1
print("Win!")
else:
print("Lose (Correct: %d)!"%(self.masterStrategy._correctDoor,))
def printStats(self):
print("Played %d games, %d won, %d lost, %d stayed, %.01f%% win ratio"%(self.gamesPlayed,self.wins,self.gamesPlayed-self.wins,self.stayed,self.wins*100.0/self.gamesPlayed))
class ManualPlayerStrategy:
def step1(self, choices):
return int(input("Choice:"))
def step2(self, choices):
return int(input("Choice:"))
class NonSwitchingPlayerStrategy:
def step1(self, choices):
self._choice = random.choice(choices)
return self._choice
def step2(self, choices):
return next(x for x in choices if x == self._choice)
class SwitchingPlayerStrategy:
def step1(self, choices):
self._choice = random.choice(choices)
return self._choice
def step2(self, choices):
return next(x for x in choices if x != self._choice)
if __name__ == '__main__':
player_strategies = {
'manual': ManualPlayerStrategy(),
'switch': SwitchingPlayerStrategy(),
'nonswitch': NonSwitchingPlayerStrategy(),
}
rounds = int(sys.argv[1])
player_strategy = player_strategies[sys.argv[2]]
game = Game(GameMasterStrategy(), player_strategy)
for _ in range(rounds):
game.play()
game.printStats()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment