Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
Try all the permutations! - no libraries, no itertools solution in Creative category for Cryptarithmetic Puzzle by FlamyDev
class Candidate:
_d = None
def __init__(self, permutation, letters: tuple[str]):
self._d = {l: v for v, l in zip(permutation, letters)}
def fulfills_all_conditions_for(self, words):
carry = 0
N = max(map(len, words))
y = []
for i in range(1, N+1):
calc = carry
for word in words[:-1]:
calc += self[word[-i]] if i <= len(word) else 0
carry, calc = divmod(calc, 10)
if calc != self[words[-1][-i]]:
return False
y.append(calc)
if carry > 0:
y.append(carry)
y = y[::-1]
return all(self[word[0]] != 0 for word in words) and all(self[c] == v for c, v in zip(words[-1], y))
def __getitem__(self, key):
return self._d[key]
@property
def solution(self):
return self._d
class PermutationsExhausted(Exception):
pass
class Brutus:
@staticmethod
def go(words: list[str]):
def gen_permutations(pool: set, r=[]):
if len(pool) == 1:
yield [pool.pop(),] + r
for x in pool:
yield from gen_permutations(pool - {x}, r=r+[x,])
letters = list(set(list("".join(words))))
for perm in gen_permutations(set(range(10))):
candidate = Candidate(perm, letters)
if candidate.fulfills_all_conditions_for(words):
return candidate.solution
else:
raise PermutationsExhausted()
def cryptarithm_solver(words: str) -> dict[str, int]:
return Brutus.go(words)
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!")
Sept. 29, 2024
Comments: