[ create a new paste ] login | about

Link: http://codepad.org/qfttpOqE    [ raw code | output | fork ]

azumih - Python, pasted on Feb 21:
#! /usr/bin/env python
# a naive kind of simulation for Monty Hall problem

import random


class Game(object):
    def __init__(self):
        self.car      = random.randint(0, 2)
        self.selected = -1
        self.opened   = -1

    def carDoorNo(self): return self.car

    def selectDoor(self, doorNo): self.selected = doorNo

    def openGoatDoor(self):
        candidates = []
        for i in xrange(0, 3):
            if i == self.selected: continue
            if i == self.car: continue
            candidates.append(i)
        self.opened = candidates[random.randint(0, len(candidates) - 1)]
        return self.opened

    def changeSelection(self):
        for i in xrange(0, 3):
            if i != self.selected and i != self.opened:
                self.selected = i
                break
        return self.selected

    def isWon(self):
        return self.selected == self.car


def simulate(numTrial, changeSelection):
    numWon = 0
    for i in xrange(numTrial):
        game = Game()
        game.selectDoor(random.randint(0, 2))
        game.openGoatDoor()
        if (changeSelection): game.changeSelection()
        if (game.isWon()): numWon += 1
    return numWon


print('#won switching: %d', simulate(1024, True))
print('#won staying: %d', simulate(1024, False))


Output:
1
2
('#won switching: %d', 680)
('#won staying: %d', 346)


Create a new paste based on this one


Comments: