James Mayfield gives this clever equation in the August 2006 issue of Word Ways1:

BEAR + RARE + ERE = RHYME

It's an alphametic: a valid equation where each digit has been replaced by an uppercase letter. Each letter represents a different digit. How do we replace the uppercase letters by digits to reconstruct the valid equation?

If A=5, B=7, E=9, H=0, M=8, R=1 and Y=3 then:

 7951
 1519
+ 919
-----
10389

In his article, Mayfield gives 94 additional narrative alphametics that have a built-in association between the words at the left-hand side and the word at the right-hand side of the equation, including the remarkable:

BRUTUS + STABS = CAESAR

He provides no answers, but if you get stuck you can derive them using this nifty calculator2.

Assignment

A word (str) is a sequence of uppercase letters in which the same letter may appear more than once.

A sum of words (str) is a sequence of words that are separated by plus signs (+). There is a single space before and after each plus sign.

The problem (str) of an alphametic is an equation with a sum of two or more words at the left-hand side and a word at the right-hand side. There is a single space before and after the equal sign (=).

The alphabet (str) of an alphametic consists of all uppercase letters in the problem of the alphametic. Each letter appears just once and the letters are in alphabetic order.

A solution (str) of an alphametic consists of a sequence of different digits. Each digit corresponds to the letter at the corresponding position in the alphabet of the alphametic, so the number of digits in the solution must be equal to the number of letters in the alphabet.

Your task:

Example

>>> alphabet('BEAR + RARE + ERE = RHYME')
'ABEHMRY'
>>> alphabet('BRUTUS + STABS = CAESAR')
'ABCERSTU'

>>> number('BEAR', 'ABEHMRY', '5790813')
7951
>>> number('RARE', 'ABEHMRY', '5790813')
1519
>>> number('ERE', 'ABEHMRY', '5790813')
919
>>> number('RHYME', 'ABEHMRY', '5790813')
10389

>>> numbers('BEAR + RARE + ERE', 'ABEHMRY', '5790813')
(7951, 1519, 919)
>>> numbers('BRUTUS + STABS', 'ABCERSTU', '75638921')
(581219, 92759)

>>> word(7951, 'ABEHMRY', '5790813')
'BEAR'
>>> word(1519, 'ABEHMRY', '5790813')
'RARE'
>>> word(919, 'ABEHMRY', '5790813')
'ERE'
>>> word(10389, 'ABEHMRY', '5790813')
'RHYME'

>>> outcome('BEAR + RARE + ERE', 'ABEHMRY', '5790813')
'RHYME'
>>> outcome('BRUTUS + STABS', 'ABCERSTU', '75638921')
'CAESAR'

>>> issolution('5790813', 'BEAR + RARE + ERE = RHYME')
True
>>> issolution('75638921', 'BRUTUS + STABS = TIBERIUS')
False

Resources