Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
Using permutations class from itertools module solution in Clear category for Cryptarithmetic Puzzle by H0r4c3
from itertools import permutations
def cryptarithm_solver(words: str) -> dict[str, int]:
left = words[0:-1]
right = words[-1]
all_letters = set("".join(left) + right)
# Solve using permutations of digits
for perm in permutations(range(10), len(all_letters)):
letter_to_digit = dict(zip(all_letters, perm))
# Check for leading zeros
if any(letter_to_digit[word[0]] == 0 for word in words + [right]):
continue
# Convert words to numbers
word_values = [sum(letter_to_digit[c] * 10**i for i, c in enumerate(word[::-1])) for word in words]
right_value = sum(letter_to_digit[c] * 10**i for i, c in enumerate(right[::-1]))
# Check if the equation holds
if sum(word_values[:-1]) == right_value:
solution = {letter: letter_to_digit[letter] for letter in sorted(all_letters)}
solution = dict(sorted(solution.items(), key=lambda item: item[1]))
return solution
print("Example:")
print(cryptarithm_solver(["SEND", "MORE", "MONEY"]))
# These "asserts" are used for self-checking
assert cryptarithm_solver(["SEND", "MORE", "MONEY"]) == {
"O": 0,
"M": 1,
"Y": 2,
"E": 5,
"N": 6,
"D": 7,
"R": 8,
"S": 9,
}
assert cryptarithm_solver(["BLACK", "GREEN", "ORANGE"]) == {
"C": 0,
"O": 1,
"A": 2,
"R": 3,
"E": 4,
"G": 5,
"N": 6,
"B": 7,
"K": 8,
"L": 9,
}
assert cryptarithm_solver(["POTATO", "TOMATO", "PUMPKIN"]) == {
"U": 0,
"P": 1,
"N": 2,
"M": 3,
"A": 4,
"O": 6,
"I": 7,
"T": 8,
"K": 9,
}
assert cryptarithm_solver(["KYOTO", "OSAKA", "TOKYO"]) == {
"A": 0,
"Y": 1,
"S": 2,
"O": 3,
"K": 4,
"T": 7,
}
print("The mission is done! Click 'Check Solution' to earn rewards!")
Dec. 7, 2024