solve alphametic puzzles in just 9 lines of code
Yingjie Lan
lanyjie at yahoo.com
Sat Sep 25 09:59:47 EDT 2010
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
More information about the Python-list
mailing list