such as: SEND + more = = Money
9567 + 1085 = = 10652
- Letters and numbers one by one correspond
- The first letter is not 0.
Solution:
ImportRe fromItertoolsImportpermutationsdefSolve (Puzzle): Puzzle=puzzle.upper () words= Re.findall ('[a-z]+', puzzle) Unique_characters= Set ("'. Join (words))assertLen (unique_characters) <= 10,'Too Many letters'first_letters= {Word[0] forWordinchwords} n=Len (first_letters) sorted_characters="'. Join (First_letters) + "'. Join (Unique_characters-first_letters) characters= Tuple (ord (c) forCinchsorted_characters) Digits= Tuple (ord (str (c)) forCinchRange (10) ) Zero=Digits[0] forGuessinchpermutations (digits, Len (characters)):ifZero not inchguess[:n]: Equation=puzzle.translate (Dict (Zip (characters, guess ))ifeval (equation):returnequationif __name__=='__main__': Puzzle="Send + more = = Money" Try: Print(Puzzle.upper ()) Solution=solve (puzzle)ifSolution:Print(solution)Else: Print("Match This") exceptException as E:Print("Error:"+str (e))
A few notes:
itertools. permutations (iterabler=none ), returns an iterator that extracts an ordered combination of R elements from the iterable
For example: List ([permutations], 2), [(1, 2), (1, 3), (2, 1), (2, 3), (3, 1) , (3, 2)]
Similar to the itertools.combinations(iterable, r=None) -> 有序组合
For example: list ([combinations], 2), [(1, 2), (1, 3), (2, 3)]
str.Translate(map ), follow the map's corresponding relationship for character substitution
A map is generally a dictionary whose keys and values are decimal representations of ASCII characters,
For example "abc123". Translate ({97:65, 98:97}), ' Aac123 '
map can be generated by Str.maketrans ()
For example: Str.maketrans (' 123 ', ' abc '), {49:97, 50:98, 51:99}
This example is generated by means of Ord, zip, Dict.
zip(*iterables), returns a tuple iterator,
Example: List (Zip ([+], ' abc '), [(1, ' a '), (2, ' B '), (3, ' C ')]
list (Zip (' ABC ', ' xy ')), [(' A ', ' X '), (' B ', ' y '), whichever is less
ord(string), int
For example: Ord (' A '), Ord (' 1 ')
Eval(expression, Globals=none, Locals=none) parse the expression string into a Python expression (which is equivalent to removing the outermost layer of quotation marks)
For example, eval (' 2 '), eval (' 1+1==2 '), eval (' ""), " +"
repr (object) is just the opposite of Eval, with a single layer of quotation marks for the object (Repr (object)) = = Object
Exec (object) Executes the python statement stored in the string
For example, exec (' Print (' "Hello ') '), Hello
Python-Alphabet Math Puzzles