| 1 | from itertools import permutations |
| 2 | |
| 3 | |
| 1 | 4 | def solve(puzzle: str) -> dict[str, int] | None: |
| 2 | | pass |
| 5 | """ |
| 6 | Solve an alphametics puzzle. |
| 7 | |
| 8 | Args: |
| 9 | puzzle (str): A string representing the alphametics puzzle (e.g., "SEND + MORE == MONEY") |
| 10 | |
| 11 | Returns: |
| 12 | dict[str, int] | None: A dictionary mapping letters to digits if a solution is found, otherwise None |
| 13 | """ |
| 14 | # Parse the puzzle |
| 15 | if '==' not in puzzle: |
| 16 | return None |
| 17 | |
| 18 | left_side, right_side = puzzle.split('==') |
| 19 | left_side = left_side.strip() |
| 20 | right_side = right_side.strip() |
| 21 | |
| 22 | # Extract words (remove operators like +, -, etc.) |
| 23 | words = [word for word in left_side.split() if word.isalpha()] + [right_side] if right_side.isalpha() else [] |
| 24 | |
| 25 | # Edge Case: No valid words found |
| 26 | if not all(word.isalpha() for word in words) or not words: |
| 27 | return None |
| 28 | |
| 29 | # Get all unique letters |
| 30 | unique_letters = set(''.join(words)) |
| 31 | |
| 32 | # Edge Case: More than 10 unique letters (impossible to assign unique digits) |
| 33 | if len(unique_letters) > 10: |
| 34 | return None |
| 35 | |
| 36 | # Get first letters of each word (can't be zero) |
| 37 | first_letters = {word[0] for word in words} |
| 38 | |
| 39 | # Try all digit permutations for the unique letters |
| 40 | for perm in permutations(range(10), len(unique_letters)): |
| 41 | mapping = dict(zip(unique_letters, perm)) |
| 42 | |
| 43 | # Edge Case: Leading zero in any word |
| 44 | if any(mapping[word[0]] == 0 for word in words): |
| 45 | continue |
| 46 | |
| 47 | # Convert words to numbers using the current mapping |
| 48 | numbers = [] |
| 49 | for word in words: |
| 50 | num = 0 |
| 51 | for char in word: |
| 52 | num = num * 10 + mapping[char] |
| 53 | numbers.append(num) |
| 54 | |
| 55 | # Check if the equation is satisfied |
| 56 | # The last number is the result, the rest are operands |
| 57 | if sum(numbers[:-1]) == numbers[-1]: |
| 58 | return mapping |
| 59 | |
| 60 | # Edge Case: No solution found |
| 61 | return None |
| 62 | # Handled Edge Cases: Invalid puzzle format, non-alphabetic words, more than 10 unique letters, leading zeros, no solution found |