As a quick diversion from my Project Euler/Haskell posts, I’m writing an entry on my monty hall problem proof that I wrote in Python a little while back. As I warned you in the past my programming skills are a little bit rusty*, and at the time of writing this solver it was my first Python code in about a year. (*Arguably the product of switching between languages to often.) Therefore the code is probably mediocre at best, which might be an overstatement. Anyway, the following is the fairly simple python code.
def game():
i = 0
switch_car_count = 0
car_count = 0
while i < 1000:
doors = ['goat', 'car', 'goat' ]
rand = random.randint(0, 2)
door = doors[rand]
del doors[rand]
doors.remove('goat')
door2 = doors[0]
i = i + 1
if door == 'car':
car_count = car_count + 1
if door2 == 'car':
switch_car_count = switch_car_count + 1
return [car_count, switch_car_count]
def results(total_count, total_switch_count, compare):
average_count = total_count / 1000
average_switch_count = total_switch_count / 1000
print average_count
print average_switch_count
print compare
def main():
i = 0
total_count = 0
total_switch_count = 0
compare = 0
while i < 1000:
[car_count, switch_car_count] = game()
total_count = car_count + total_count
total_switch_count = switch_car_count + total_switch_count
i = i + 1
if car_count < switch_car_count:
compare = compare + 1
results(total_count, total_switch_count, compare)
main()
This yields the output:
333
666
1000
These values respectfully represent average winnings with keeping original, average winnings with switching, and total number of times switching was the better yielding option.
This code should be fairly straight forward to anybody familiar with Python basics. Any questions or suggestions about my code should be posted in the comments and I will hopefully reply promptly.