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…
- Finds all the letters in the puzzle with the
re.findall()
function - Find all the unique letters in the puzzle with sets and the
set()
function - Checks if there are more than 10 unique letters (meaning the puzzle is definitely unsolvable) with an
assert
statement - Converts the letters to their ASCII equivalents with a generator object
- Calculates all the possible solutions with the
itertools.permutations()
function - Converts each possible solution to a Python expression with the
translate()
string method - Tests each possible solution by evaluating the Python expression with the
eval()
function - Returns the first solution that evaluates to
True
…in just 14 lines of code.
Get hands-on with 1400+ tech skills courses.