Day 21 of the Anvil Advent Calendar

Build a web app every day until Christmas, with nothing but Python!

Will you get an orange in your stocking? Or some coal?

In front of you are three stockings. You know that one of them contains an orange (the traditional Christmas treat for those on Santa’s Nice List), and two contain coal (for those who’ve been…. Not So Nice). You pick one without opening it, at which point Santa opens one of the other to reveal a piece of coal. He then asks if you want to switch your choice to the other unopened stocking. If you want the best possible chance at getting the orange, should you switch?

A screenshot of the app.

This is the classic Monty Hall Problem, one of the most well-known examples of conditional probability. For today’s Advent Calendar, I built an app where you can play the game yourself!

To see how it works, clone it here and check out the source code:

How it works

When you load up the app, it chooses which of the stockings has the orange hidden in it. Then, as you step through the process of choosing a stocking, revealing a piece of coal, and deciding whether or not to switch, the app keeps track of whether you won or lost and whether you switched or not. When you’re done, you can start again by hitting ‘Refresh your stocking’ and play another round!

As you play, the statistics displayed at the bottom will change to reflect your track record, and you can see what happens over time as the overall probabilities begin to become apparent.

I may have got carried away here.

I may have got carried away here.

All this is done in client code, by switching around the source property of the Image components in question, and altering the visibility of the buttons at each stage in the process. The only tricky part was keeping track of which stocking was which!


Give the Gift of Python

Share this post: