### Random Post

### Recent Posts

### Recent Comments

### Archives

### Categories

- article (11)
- enigma (1,609)
- enigma-book-1982 (70)
- misc (5)
- project euler (2)
- puzzle (90)
- puzzle# (173)
- site news (76)
- tantalizer (189)
- teaser (7)
- today (1)

### Site Stats

- 310,317 hits

Programming Enigma Puzzles

8 January 2013

Posted by on **From New Scientist #1206, 19th June 1980** [link]

Below is an addition sum with letters substituted for digits. The same letter stands for the same digit wherever it appears, and different letters stand for different digits.

Write the sum out with numbers substituted for letters.

**Enigma 21** is also called “Addition: letters for digits”.

[enigma63]

%d bloggers like this:

The following Python program tries all permutations. It runs in 1.1s.

Solution:The sum is 8308440 + 8333218 + 8302040 + 8333260 = 33276958.Having done a couple of these sums with letters substituted for digits recently I thought it would be fun to write a general solver for them.

The following code takes a straightforward right-to-left approach on the columns of the sum, recursively examining the possibilities for each column. There are three interfaces to it:

`_substituted_sum()`

is the core of the algorithm, but it assumes its arguments are nicely formed.`substituted_sum()`

is a friendlier way to run the algorithm, it makes sure the arguments are valid and fills out sensible default values.`SubstitutedSum()`

wraps the previous function as a class so you don’t have to remember the terms in sum itself, and provides some handy functions for reporting solutions.Gratifyingly this solution runs in 139ms, nearly 10× faster than the previous solution.

I will probably clean this up, add some more documentation and put it in the

enigma.pylibrary for future use.