A group of friends and I decided we wanted to play the lottery.
We found the closest convenience store and purchased a fistful of tickets. “If we buy more tickets, that doubles our chances to win!”
The numbers were called.
I know… we were shocked as well.
That raised an interesting question though… what if we could have a computer play the lottery? More specifically, how long would it take for a computer to play itself and win?
Python makes this pretty easy. In this lab, we’re going to use Python’s random module and build two function. The first will generate six random numbers between 1 and 69 and return an array:
Using random’s ‘randint’ module, we can first generate six ‘winning’ numbers, as well as any subsequent ‘tickets’.
Once this is working, we’ll create a second function that will generate ‘guesses’ until a guess matches the six winning numbers:
The code above generates six “winning” numbers and saves them to memory. Once this is complete, it will run a while loop to generate “tickets” or “guesses” until it finds a winning match. I was also curious to see how hard it would be to match 1, 2, 3 or more numbers since these can be counted as ‘partial wins’. I created a “Highest Match” variable to track this as well. Once everything was set up, it was time to execute!
The results were quite interesting. Getting to one correct number took a fraction of a second (as expected) Getting two or three correct numbers was pretty easy as well. Even four or five correct guesses only took about 30 thousand tickets to achieve. (A few seconds in this experiment)
But six…. six correct numbers is hard. Like… really hard.
I let this code execute for the rest of the day. Then I let it execute all night. Then all day again. Then all night. It still hadn’t gotten to six correct numbers.
On the third day, I was about to give up, but I decided to give it on more night. The next day, when I woke up, Success!
After 288,977,746 tickets purchased, the computer had finally won the lottery. Checking the Powerball odds, this was actually lucky.
Moral of the story: unless you want to buy 288 million lottery tickets, don’t expect to win the grand prize.