CMU Coding Bootcamp
at main 1.7 kB view raw
1def solvesCryptarithm(puzzle: str, solution: str) -> bool: 2 """Check if a cryptarithm puzzle is solved correctly. 3 4 Args: 5 puzzle (str): The cryptarithm puzzle. 6 solution (str): The solution to the puzzle. 7 8 Returns: 9 bool: True if the puzzle is solved correctly, False otherwise. 10 """ 11 left = puzzle.split(" + ")[0].strip() 12 right = puzzle.split(" + ")[1].split(" = ")[0].strip() 13 result = puzzle.split(" + ")[1].split(" = ")[1].strip() 14 scores = list(solution) 15 for score, letter in enumerate(scores): 16 print(score, letter) 17 left = left.replace(letter, str(score)) 18 right = right.replace(letter, str(score)) 19 result = result.replace(letter, str(score)) 20 print(left, right, result) 21 try: 22 return int(left) + int(right) == int(result) 23 except ValueError: 24 return False 25 26 27print("Testing solvesCryptarithm()...", end="") 28# 9567 + 1085 = 10652 29assert solvesCryptarithm("SEND + MORE = MONEY", "OMY--ENDRS") == True 30 31# 201689 + 201689 = 403378 32assert solvesCryptarithm("NUMBER + NUMBER = PUZZLE", "UMNZP-BLER") == True 33 34# 91542 + 3077542 = 3169084 35assert solvesCryptarithm("TILES + PUZZLES = PICTURE", "UISPELCZRT") == True 36 37# 8456 + 1074 = 10542 (False) 38assert solvesCryptarithm("SEND + MORE = MONEY", "OMY-ENDRS") == False 39 40# 9567 + 1085 = 1062 (False) 41assert solvesCryptarithm("SEND + MORE = MONY", "OMY--ENDRS") == False 42 43# No S in solution 44assert solvesCryptarithm("SEND + MORE = MONEY", "OMY--ENDR-") == False 45print("Passed!")