Advertisement
xathrya

Alphametic Solver

Apr 20th, 2018
130
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.18 KB | None | 0 0
  1. from z3 import *
  2. import string
  3.  
  4. # Solve the alphametic with following pattern
  5. #    SEND + MORE = MONEY
  6.  
  7. def create_term_sum(charmap, term):
  8.     rev_term = list(reversed(term))
  9.     result = charmap[rev_term[0]]
  10.  
  11.     coeff = 10
  12.     for i in range(1, len(rev_term)):
  13.         result = result + coeff*charmap[rev_term[i]]
  14.         coeff *= 10
  15.     return result
  16.  
  17. def print_term(model, charmap, term):
  18.     line = "{} = {}"
  19.     left = term
  20.     right = ""
  21.     for i in range(len(term)):
  22.         right += "{}".format(model[charmap[term[i]]])
  23.     print(line.format(left, right))
  24.  
  25.  
  26. if __name__ == '__main__':
  27.     sentence = input('Enter equation: ')
  28.  
  29.     while sentence != "EXIT":
  30.         charmap = {}
  31.         solver = Solver ()
  32.  
  33.         # Declare variables, actually map of characters and Z3 Ints
  34.         print("*** Split the setence ***")
  35.         sequence = "".join(filter(lambda c: c.isupper(), set(sentence)))
  36.         for char in sequence:
  37.             charmap[char] = Int(char)
  38.  
  39.         # Make all character disctinct
  40.         print("*** Applying distinct ***")
  41.         solver.add(Distinct(list(charmap.values())))
  42.  
  43.         # Make all character in correct range
  44.         print("*** Applying range ***")
  45.         for item in charmap.values():
  46.             solver.add(And(0 <= item, item <= 9))
  47.            
  48.         # Create constraints
  49.         # SEND + MORE = MONEY
  50.         # left = [SEND, MORE]
  51.         # right = MONEY
  52.         left, right = sentence.replace(' ','').split('=')
  53.         left = left.split('+')
  54.  
  55.         # But for the first in each term should not be 0
  56.         for term in left:
  57.             solver.add(And(0 < charmap[term[0]], charmap[term[0]] <= 9))
  58.         solver.add(And(0 < charmap[right[0]], charmap[right[0]] <= 9))
  59.  
  60.         solver.add(sum([create_term_sum(charmap, term) for term in left]) == create_term_sum(charmap, right))
  61.        
  62.         print("*** Solving ***")
  63.         if solver.check() == sat:
  64.             model = solver.model()
  65.             for term in left:
  66.                 print_term(model, charmap, term)
  67.             print("---------------------")
  68.             print_term(model, charmap, right)
  69.  
  70.         sentence = input('Enter equation: ')
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement