'The Goat and the Car' puzzle solved in Python -- was: [GERMAN] "ziegenpro

gbreed at cix.compulink.co.uk gbreed at cix.compulink.co.uk
Fri Mar 8 06:14:55 EST 2002


Oh, this is the zeigenproblem thread?  I was ignoring it because it 
purported to be in German.

> Le 07/03/02 à 19:28, stefan antoni écrivit:
> > sorry that i won't be able to explain this in english, i don't know 
> > the
> > name of this problem in english, and the website which is about this
> > problem is also in german.

It's called the Monty Hall Problem.

> > i am still going to school, and we talked about this problem in a math
> > lesson. since i haven't got a basic-interpreter, i'd like to translate
> > this code into python, but i don't understand the code.

Here's my monty.py from a while back.  It gives the result

you got 66642 cars and 33358 goats
you were right 66% of the time

so the stratagem works!


"""Python script to test the Monty Hall Problem"""
import whrandom
nCars = 0
nGoats = 0
for each in xrange(100000):

  # decide where the car is
  carPosition = whrandom.randint(1,3)

  # choose a door
  myFirstChoice = whrandom.randint(1,3)

  # Monty chooses a door
  # not your door or the one with the car behind
  for door in (1,2,3):
    if door not in (carPosition, myFirstChoice):
      montyChoice = door

  # change your mind
  for door in (1,2,3):
    if door not in (montyChoice, myFirstChoice):
      myFinalChoice = door

  # see what you won!
  if myFinalChoice == carPosition:
    nCars = nCars + 1
  else:
    nGoats = nGoats + 1

print "you got %i cars and %i goats" % (nCars, nGoats)
print "you were right %i%% of the time" % (nCars*100/(nCars+nGoats))




More information about the Python-list mailing list