| 1 | from itertools import permutations |
| 2 | |
| 1 | 3 | def solve(puzzle: str) -> dict[str, int] | None: |
| 2 | | pass |
| 4 | """ |
| 5 | Solve an alphametics puzzle. |
| 6 | |
| 7 | Args: |
| 8 | puzzle: A string representing the alphametics puzzle (e.g., "SEND + MORE == MONEY") |
| 9 | |
| 10 | Returns: |
| 11 | A dictionary mapping letters to digits that solves the puzzle, or None if no solution exists. |
| 12 | |
| 13 | Example: |
| 14 | >>> solve("SEND + MORE == MONEY") |
| 15 | {'S': 9, 'E': 5, 'N': 6, 'D': 7, 'M': 1, 'O': 0, 'R': 8, 'Y': 2} |
| 16 | """ |
| 17 | # Parse the puzzle |
| 18 | if "==" not in puzzle: |
| 19 | return None |
| 20 | |
| 21 | left_side, right_side = puzzle.split("==") |
| 22 | left_side = left_side.strip() |
| 23 | right_side = right_side.strip() |
| 24 | |
| 25 | # Parse the left side to extract words and operators |
| 26 | tokens = left_side.split() |
| 27 | words = [] |
| 28 | operators = [] |
| 29 | |
| 30 | for token in tokens: |
| 31 | if token in ["+", "-"]: |
| 32 | operators.append(token) |
| 33 | else: |
| 34 | words.append(token) |
| 35 | |
| 36 | words.append(right_side) |
| 37 | |
| 38 | # Edge Case: Empty puzzle or invalid format |
| 39 | if not words or not all(words): |
| 40 | return None |
| 41 | |
| 42 | # Get all unique letters |
| 43 | letters = set("".join(words)) |
| 44 | |
| 45 | # Edge Case: More than 10 unique letters (impossible to solve) |
| 46 | if len(letters) > 10: |
| 47 | return None |
| 48 | |
| 49 | # Get first letters of each word (can't be zero) |
| 50 | first_letters = {word[0] for word in words} |
| 51 | |
| 52 | # Try all possible digit assignments |
| 53 | for perm in permutations(range(10), len(letters)): |
| 54 | mapping = dict(zip(letters, perm)) |
| 55 | |
| 56 | # Edge Case: Leading digit is zero |
| 57 | if any(mapping[letter] == 0 for letter in first_letters): |
| 58 | continue |
| 59 | |
| 60 | # Convert words to numbers |
| 61 | numbers = [] |
| 62 | for word in words: |
| 63 | num = 0 |
| 64 | for letter in word: |
| 65 | num = num * 10 + mapping[letter] |
| 66 | numbers.append(num) |
| 67 | |
| 68 | # Check if the equation is satisfied |
| 69 | # Evaluate the left side expression using the actual operators |
| 70 | if len(words) == 1: |
| 71 | # Single word on left side (e.g., "WORD == RESULT") |
| 72 | left_value = numbers[0] |
| 73 | else: |
| 74 | # Multiple words with operators |
| 75 | left_value = numbers[0] |
| 76 | for i, op in enumerate(operators): |
| 77 | if op == "+": |
| 78 | left_value += numbers[i + 1] |
| 79 | elif op == "-": |
| 80 | left_value -= numbers[i + 1] |
| 81 | |
| 82 | right_value = numbers[-1] |
| 83 | |
| 84 | if left_value == right_value: |
| 85 | return mapping |
| 86 | |
| 87 | # Edge Case: No solution found |
| 88 | return None |
| 89 | # Handled Edge Cases: Empty puzzle or invalid format, More than 10 unique letters, Leading digit is zero, No solution found |