Python Programming Challenge – First to Five

Python Programming Challenge – First to Five

by Real Python basics python

We’ve partnered with our friends at Interview Cake to bring you a programming challenge to test your logic skills and abilities.

Updated 10/16/2015: Added additional challenges—cheers!

The Challenge

  1. There are two players.
  2. Each player writes a number, hidden from the other player. It can be any integer 1 or greater.
  3. The players reveal their numbers.
  4. Whoever chose the lower number gets 1 point, unless the lower number is lower by only 1, then the player with the higher number gets 2 points.
  5. If they both chose the same number, neither player gets a point.
  6. This repeats, and the game ends when one player has 5 points.

The challenge is to write a script to play this game. Knowing the rules and all your opponent’s previous numbers, can you program a strategy? (And, no - return random.randint(1, 3) is not a strategy.) You should really try playing this first with your friends - you’ll see there’s a deep human element to predicting your opponent’s choice.

Is it possible to program a strong strategy?

Want to make the strategy a bit more interesting? Add an additional constraint to the challenge so that players can only use each number once.

The Prizes

Need some motivation? We’ll be giving out prizes to the strategies that perform the best:

Although the challenge is officially over (results) you can still partake! First, see if you can beat the current winner to receive $20 off of Real Python. Second, create a web application with Flask that (a) makes it easy to add a new strategy and then (b) runs a given strategy against all the other strategies.

Grading

The grading is simple: We’ll run each strategy through the random number generator 100 times as a first screen - return random.randrange(1, 10). The strategies that beat the generator we’ll then be ran against one other in a round robin format to determine the overall winners. Be sure to test your code out in the game runner before submitting.

To submit your script, just email us a link to a secret Gist - info (at) realpython (dot) com. Good luck!

This contest is now closed. Thanks to everyone who participated, and Happy Pythoning!

🐍 Python Tricks 💌

Get a short & sweet Python Trick delivered to your inbox every couple of days. No spam ever. Unsubscribe any time. Curated by the Real Python team.

Python Tricks Dictionary Merge

What Do You Think?

Real Python Comment Policy: The most useful comments are those written with the goal of learning from or helping out other readers—after reading the whole article and all the earlier comments. Complaints and insults generally won’t make the cut here.

Keep Reading