Sorry, didn't document my code well enough.
Here is the code with an example.

Yingjie


#############Code begins###############

from itertools import permutations

def solve(puzzle):
    """solve alphametic puzzles in just 9 lines of code.
Make sure each operator is seperated from the words by
white-spaces, e.g.:

>>> solve('send + more == money')

"""
    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 permutations('0123456789', len(chars)):
        if '0' not in guess[:len(nonzeros)]:
            equation = puzzle.translate(dict(zip(chars, guess)))
            if eval(equation): return puzzle, equation

if __name__ == '__main__':
    print ('\n'.join(solve("send + more == money")))


      
-- 
http://mail.python.org/mailman/listinfo/python-list

Reply via email to