Putting It All Together

To recap: this program solves alphametic puzzles by brute force, i.e. through an exhaustive search of all possible solutions. To do this, it…

  1. Finds all the letters in the puzzle with the re.findall() function
  2. Find all the unique letters in the puzzle with sets and the set() function
  3. Checks if there are more than 10 unique letters (meaning the puzzle is definitely unsolvable) with an assert statement
  4. Converts the letters to their ASCII equivalents with a generator object
  5. Calculates all the possible solutions with the itertools.permutations() function
  6. Converts each possible solution to a Python expression with the translate() string method
  7. Tests each possible solution by evaluating the Python expression with the eval() function
  8. Returns the first solution that evaluates to True

…in just 14 lines of code.

Get hands-on with 1200+ tech skills courses.