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

Gerhard Häring gh_pythonlist at gmx.de
Thu Mar 7 14:16:08 EST 2002


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.
> 
> i want to write this basic code in python:
> http://www.google.de/search?q=cache:Uugc3CH9SOQC:home.spektracom.de/ellrich/Ziegen.htm+ziegenproblem+basic+programm&hl=de
> 
> 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.

The BASIC code hurts my eyes. I've hacked a Pythonic solution:

import random

prices = ["goat", "goat", "car"]

iterations = 2000
times_won = 0

for i in range(iterations):
    random.shuffle(prices)
    mypick = random.randrange(3)
    
    # Moderator chooses a 'goat door' randomly
    while 1:
        goat_chosen_by_moderator = random.randrange(3)
        if prices[goat_chosen_by_moderator] != "car" and \
            goat_chosen_by_moderator != mypick:
            break

    # We take the other door!
    door_numbers = range(3)
    door_numbers.remove(mypick)
    door_numbers.remove(goat_chosen_by_moderator)
    mypick = door_numbers[0]

    # Is there a a car?
    if prices[mypick] == "car":
        times_won += 1

print float(times_won) / iterations

Gerhard
-- 
This sig powered by Python!
Außentemperatur in München: 9.7 °C      Wind: 4.9 m/s




More information about the Python-list mailing list