Photo by Ravi Kumar on Unsplash

Using Python to Solve the Pragmatic Programmers Quizzes

Get a Leg Up on Those Math Questions

Miki Tebeka
3 min readOct 27, 2021

--

📚 Connect with us. Want to hear what’s new at The Pragmatic Bookshelf? Sign up for our newsletter. You’ll be the first to know about author speaking engagements, books in beta, new books in print, and promo codes that give you discounts of up to 40 percent.

My publishing house The Pragmatic Bookshelf is posting short math teasers on Twitter.

It’s fun to try to solve these teasers, but I wondered how challenging it would be to write a program that solves them. Turns out — it’s not that difficult.

The Wandering Digit

Let’s start with an easier case to program, I call it “the wandering digit” teaser. Here’s an example:

A digit has wandered from its proper place. Identify and return it home so the equation is correct.

5920 + 894 = 146614

We’ll try all possible combinations to move a digit to somewhere else, and then call Python’s built-in eval to calculate the result:

Let’s try it out:

One of the main takeaways is to convert the input from a human-readable format to a format that’s easier for a machine to work with. In this case — we removed the spaces from the input.

Getting a Number from a List

Another type of teaser is to get to a number from a list of other numbers using math operations.

Here’s an example:

Combine 5, 5, 2, and 1 to make 15. You may add, subtract, multiply, divide and use parentheses. Use each digit once.

No: exponentiation, logs, factorials, decimals, rotating numbers (9s to make 6), or placing two digits together (1 and 4 doesn’t make 14).

The program is going to generate all the possible combinations of the numbers, with the math operators (for example, +) and placement of parentheses. Once we have an expression such as '5*5/2+1' we can use the built-in eval to calculate the result.

First, we’ll start by generating all the permutations of operators given a sequence of digits.

I love the combination of generators and recursion — they create short and powerful code.

Next, let’s add all the possible combinations of parentheses. For example, if we have 1+2*3, we'll get (1+2)*3, (1+2*3), 1+(2*3).

Last, we’re going to go over all the permutations of the numbers. For example for (1, 2, 3) we'll get (1, 2, 3), (1, 3, 2), (2, 1, 3), (2, 3, 1), (3, 1, 2), (3, 2, 1). We don't need to write any code for this, there's already a permutations function in the built-in itertools module.

Here’s the top-level function, that generates all the possible math expressions and finds the one that equals the desired result:

Let’s try it out on our puzzle:

I had as much fun writing this code as I had trying to solve the teasers by myself. I hope you enjoy reading this post :)

--

--