| 1 | 1 | def solve(puzzle: str) -> dict[str, int] | None: |
| 2 | | pass |
| 2 | # Parse the puzzle |
| 3 | if "==" in puzzle: |
| 4 | left, right = puzzle.split("==") |
| 5 | right = right.strip() |
| 6 | else: |
| 7 | parts = puzzle.split("=") |
| 8 | if len(parts) != 2: |
| 9 | return None |
| 10 | left, right = parts[0], parts[1] |
| 11 | |
| 12 | left = left.strip() |
| 13 | right = right.strip() |
| 14 | |
| 15 | # Handle both + and - operations |
| 16 | if " + " in left: |
| 17 | addends = [x.strip() for x in left.split(" + ")] |
| 18 | operation = "add" |
| 19 | elif " - " in left: |
| 20 | addends = [x.strip() for x in left.split(" - ")] |
| 21 | operation = "subtract" |
| 22 | else: |
| 23 | addends = [left] |
| 24 | operation = "add" |
| 25 | |
| 26 | # Edge Case: Empty puzzle or malformed format |
| 27 | if not addends or not right: |
| 28 | return None |
| 29 | |
| 30 | # Collect all unique letters |
| 31 | letters = set() |
| 32 | for word in addends + [right]: |
| 33 | letters.update(word) |
| 34 | |
| 35 | # Edge Case: More than 10 unique letters (impossible to solve) |
| 36 | if len(letters) > 10: |
| 37 | return None |
| 38 | |
| 39 | first_letters = {word[0] for word in addends + [right]} |
| 40 | |
| 41 | # Edge Case: Single letter words |
| 42 | for word in addends + [right]: |
| 43 | if len(word) == 0: |
| 44 | return None |
| 45 | |
| 46 | letters = list(letters) |
| 47 | |
| 48 | def is_valid_solution(mapping): |
| 49 | # Check if any first letter maps to 0 |
| 50 | # Edge Case: Leading digit cannot be zero |
| 51 | for letter in first_letters: |
| 52 | if mapping[letter] == 0: |
| 53 | return False |
| 54 | |
| 55 | # Convert words to numbers |
| 56 | numbers = [] |
| 57 | for word in addends: |
| 58 | num = 0 |
| 59 | for char in word: |
| 60 | num = num * 10 + mapping[char] |
| 61 | numbers.append(num) |
| 62 | |
| 63 | result_num = 0 |
| 64 | for char in right: |
| 65 | result_num = result_num * 10 + mapping[char] |
| 66 | |
| 67 | # Check if the equation holds |
| 68 | if operation == "add": |
| 69 | return sum(numbers) == result_num |
| 70 | else: # subtract |
| 71 | return numbers[0] - sum(numbers[1:]) == result_num |
| 72 | |
| 73 | # Generate all possible digit assignments |
| 74 | from itertools import permutations |
| 75 | |
| 76 | # Edge Case: No solution exists for the given puzzle |
| 77 | for perm in permutations(range(10), len(letters)): |
| 78 | mapping = dict(zip(letters, perm)) |
| 79 | if is_valid_solution(mapping): |
| 80 | return mapping |
| 81 | |
| 82 | return None |
| 83 | # Handled Edge Cases: Empty puzzle or malformed format, More than 10 unique letters (impossible to solve), Single letter words, Leading digit cannot be zero, No solution exists for the given puzzle |