Created
October 27, 2020 20:32
-
-
Save rabbitix/62db9e8378cac9878619eba666555198 to your computer and use it in GitHub Desktop.
code for word puzzle solver in python
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import re | |
import itertools | |
def solve(puzzle): | |
# find all words in it | |
words = re.findall('[A-Z]+', puzzle.upper()) | |
# make a list of unique chars | |
unique_characters = set(''.join(words)) | |
# check if entered chars are more than 10 | |
assert len(unique_characters) <= 10, 'Too many letters' | |
# make a unique list of first letter of every words | |
first_letters = {word[0] for word in words} | |
# len of first letters list | |
n = len(first_letters) | |
# | |
sorted_characters = ''.join(first_letters) + ''.join(unique_characters - first_letters) | |
characters = tuple(ord(c) for c in sorted_characters) | |
digits = tuple(ord(c) for c in '0123456789') | |
zero = digits[0] | |
print( "there is ",len(list(itertools.permutations(digits, len(characters))))," permutations") | |
for guess in itertools.permutations(digits, len(characters)): | |
if zero not in guess[:n]: | |
trns = dict(zip(characters, guess)) | |
equation = puzzle.translate(trns) | |
if eval(equation): | |
return equation | |
if __name__ == '__main__': | |
import sys | |
for puzzle in sys.argv[1:] : | |
# for puzzle in ["SEND + MORE == MONEY"]: | |
print(puzzle) | |
solution = solve(puzzle) | |
if solution: | |
print(solution) | |
else: | |
print(f'No solution found for {puzzle}') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment