solve alphametic puzzles in just 9 lines of code

Y

Yingjie Lan

Hi,

I am teaching Python this semester and
as I am trying to explain the code by
Raymond Hettinger, I need to make it
simpler (this is an introductory course).
And it ends up to be just 9 lines of code.

Just for fun. See also:

http://diveintopython3.org/advanced-iterators.html


Regards,
Yingjie

############Code starts here###########

import itertools
def solve(puzzle):
"solve alphametic puzzles in just 9 lines of code."
words = [w for w in puzzle.split() if w.isalpha()]
nonzeros = {w[0] for w in words}
others = {a for a in ''.join(words) if a not in nonzeros}
chars = [ord(c) for c in nonzeros]+[ord(c) for c in others]
assert len(chars) <= 10, 'Too many letters'
for guess in itertools.permutations('0123456789', len(chars)):
if '0' not in guess[:len(nonzeros)]:
equation = puzzle.translate(dict(zip(chars, guess)))
if eval(equation): return equation
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,436
Messages
2,571,696
Members
48,796
Latest member
Greg L.
Top