Advertisement
makispaiktis

Cryptarithmetic Puzzle

Apr 27th, 2021 (edited)
583
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 5.75 KB | None | 0 0
  1. '''
  2. Good morning! Here's your coding interview problem for today.
  3. This problem was asked by Google.
  4. A cryptarithmetic puzzle is a mathematical game where the digits of some numbers are represented by letters.
  5. Each letter represents a unique digit.
  6. For example, a puzzle of the form:
  7.  SEND
  8. + MORE
  9. --------
  10. MONEY
  11. may have the solution:
  12. {'S': 9, 'E': 5, 'N': 6, 'D': 7, 'M': 1, 'O', 0, 'R': 8, 'Y': 2}
  13. Given a three-word puzzle like the one above, create an algorithm that finds a solution.
  14. '''
  15. from itertools import permutations
  16. from timeit import default_timer as timer
  17.  
  18. # FUNCTION 1
  19. def breakMessage(message):
  20.     # First, I have to find the '+' and '=' characters
  21.     plusIndex = message.index('+')
  22.     equalsIndex = message.index('=')
  23.     word1 = message[0 : plusIndex-1]
  24.     word2 = message[plusIndex+2 : equalsIndex-1]
  25.     word3 = message[equalsIndex+2:]
  26.     return word1, word2, word3
  27.  
  28. # FUNCTION 2
  29. def uniqueLetters(word1, word2, word3):
  30.     words = word1 + word2 + word3
  31.     unique = list()
  32.     for letter in words:
  33.         isUnique = True
  34.         for un in unique:
  35.             if letter == un:
  36.                 isUnique = False
  37.                 break
  38.         if isUnique == True:
  39.             unique.append(letter)
  40.     return unique
  41.  
  42. # FUNCTION 3
  43. def matchLists(list1, list2):
  44.     if len(list1) != len(list2):
  45.         print("Error while using function " + matchLists.__name__)
  46.     dictionary = dict()
  47.     for i in range(len(list1)):
  48.         dictionary[list1[i]] = list2[i]
  49.     return dictionary
  50.  
  51.  
  52. # FUNCTION 4
  53. def match(message):
  54.     word1, word2, word3 = breakMessage(message)
  55.     unique = uniqueLetters(word1, word2, word3)
  56.     # Now, we have a list with unique letters. Let's suppose N unique letters
  57.     # Each unique letter can take values from 0 to 9, so there are
  58.     # 10 ^ N possible arrangements. So I will create all the 10^N possible
  59.     # permutations. Each index of permutation can be from 0 to 9.
  60.     # I will equalise each permutation with the letters
  61.     N = len(unique)
  62.     perms = permutations(list(range(10)), N)
  63.     N1 = len(word1)
  64.     N2 = len(word2)
  65.     N3 = len(word3)
  66.     solutionLetters = dict()
  67.     solutionNumbers = list()
  68.  
  69.     for perm in perms:
  70.         dictionary = matchLists(unique, perm)
  71.         # print(dictionary)
  72.         number1 = 0
  73.         number2 = 0
  74.         number3 = 0
  75.         # ===============================================================================
  76.         # ===============================================================================
  77.         # Word 1 ----> Number 1
  78.         for i in range(N1):
  79.             letter = word1[i]
  80.             digit = -1
  81.             for key in dictionary:
  82.                 if letter == key:
  83.                     digit = dictionary[key]
  84.                     break
  85.             number1 += digit * (10**(N1-1-i))
  86.         # Word 2 ----> Number 2
  87.         for i in range(N2):
  88.             letter = word2[i]
  89.             digit = -1
  90.             for key in dictionary:
  91.                 if letter == key:
  92.                     digit = dictionary[key]
  93.                     break
  94.             number2 += digit * (10**(N2-1-i))
  95.         # Word 3 ----> Number 3
  96.         for i in range(N3):
  97.             letter = word3[i]
  98.             digit = -1
  99.             for key in dictionary:
  100.                 if letter == key:
  101.                     digit = dictionary[key]
  102.                     break
  103.             number3 += digit * (10**(N3-1-i))
  104.         # ===============================================================================
  105.         # ===============================================================================
  106.         # Now, I have all the 3 numbers I want
  107.         perm = [number1, number2, number3]
  108.         # print(perm)
  109.         if number1 + number2 == number3:
  110.             # print("YES, WE FOUND A SOLUTION TO THIS PROBLEM")
  111.             solutionLetters = dictionary
  112.             solutionNumbers = perm
  113.             break
  114.  
  115.     if len(solutionLetters) != 0:
  116.         # We have found a solution
  117.         return solutionLetters, solutionNumbers
  118.     else:
  119.         # There is no solution
  120.         return {}, []
  121.  
  122.  
  123. # FUNCTION 5
  124. def prettyPrint(message):
  125.     start = timer()
  126.     print("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~")
  127.     solutionLetters, solutionNumbers = match(message)
  128.     print(message)
  129.     if len(solutionLetters) != 0:
  130.         result = ""
  131.         M = len(solutionLetters)
  132.         counter = 0
  133.         for key in solutionLetters:
  134.             if counter != M - 1:
  135.                 result += key + " = " + str(solutionLetters[key]) + ", "
  136.             else:
  137.                 result += key + " = " + str(solutionLetters[key])
  138.         print("Solution for: " + result)
  139.         print(str(solutionNumbers[0]) + " + " + str(solutionNumbers[1]) + " = " + str(solutionNumbers[2]))
  140.         end = timer()
  141.         elapsed = end - start
  142.         print()
  143.         print("Execution time: " + str(round(elapsed, 4)) + " seconds.")
  144.         print("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~")
  145.         print()
  146.     else:
  147.         print("There is no solution for this problem")
  148.         print("Next time")
  149.  
  150.  
  151. # MAIN FUNCTION
  152. # RULES
  153. print("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~")
  154. print("We are trying to match letters with numbers, so we can have an acceptable addition")
  155. print("But, the user has to leave blank space between and after the symbols '+' and '='")
  156. print("One good example is: send + more = money")
  157. print("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~")
  158. print()
  159. message1 = "ab + ba = cc"
  160. prettyPrint(message1)
  161. message2 = "send + more = money"
  162. prettyPrint(message2)
  163. message3 = input("Message: ")
  164. prettyPrint(message3)
  165.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement