| 1 | import itertools |
| 2 | import re |
| 3 | |
| 1 | 4 | def solve(puzzle: str) -> dict[str, int] | None: |
| 2 | | pass |
| 5 | # Parse the puzzle into components |
| 6 | # Edge Case: Invalid puzzle format |
| 7 | if '==' not in puzzle: |
| 8 | # Try to handle single equation with '+' |
| 9 | if '=' in puzzle and '+' in puzzle: |
| 10 | parts = puzzle.replace(' ', '').replace('==', '=').split('=') |
| 11 | if len(parts) != 2: |
| 12 | return None |
| 13 | left_side, right_side = parts[0], parts[1] |
| 14 | addends = left_side.split('+') |
| 15 | else: |
| 16 | return None |
| 17 | else: |
| 18 | parts = puzzle.replace(' ', '').split('==') |
| 19 | if len(parts) != 2: |
| 20 | return None |
| 21 | left_side, right_side = parts[0], parts[1] |
| 22 | # Handle both + and potentially other operators |
| 23 | if '+' in left_side: |
| 24 | addends = left_side.split('+') |
| 25 | else: |
| 26 | # For cases like ABC==XYZ (no operator) |
| 27 | addends = [left_side] |
| 28 | |
| 29 | # Extract all unique letters |
| 30 | letters = set(re.findall(r'[A-Z]', puzzle)) |
| 31 | |
| 32 | # Edge Case: No letters in puzzle |
| 33 | if not letters: |
| 34 | return None |
| 35 | |
| 36 | # Find first letters of each word (can't be zero) |
| 37 | first_letters = set() |
| 38 | for word in addends + [right_side]: |
| 39 | if word: |
| 40 | first_letters.add(word[0]) |
| 41 | |
| 42 | # Edge Case: More than 10 unique letters (impossible to solve) |
| 43 | if len(letters) > 10: |
| 44 | return None |
| 45 | |
| 46 | # Get all digits |
| 47 | digits = range(10) |
| 48 | |
| 49 | # Generate all possible permutations of digits for the letters |
| 50 | for perm in itertools.permutations(digits, len(letters)): |
| 51 | mapping = dict(zip(letters, perm)) |
| 52 | |
| 53 | # Edge Case: Leading zero |
| 54 | if any(mapping[letter] == 0 for letter in first_letters): |
| 55 | continue |
| 56 | |
| 57 | # Calculate the values of addends |
| 58 | addend_values = [] |
| 59 | valid = True |
| 60 | |
| 61 | for word in addends: |
| 62 | num = 0 |
| 63 | for char in word: |
| 64 | if char in mapping: |
| 65 | num = num * 10 + mapping[char] |
| 66 | else: |
| 67 | valid = False |
| 68 | break |
| 69 | if not valid: |
| 70 | break |
| 71 | addend_values.append(num) |
| 72 | |
| 73 | if not valid: |
| 74 | continue |
| 75 | |
| 76 | # Calculate the value of result |
| 77 | result_value = 0 |
| 78 | for char in right_side: |
| 79 | if char in mapping: |
| 80 | result_value = result_value * 10 + mapping[char] |
| 81 | else: |
| 82 | valid = False |
| 83 | break |
| 84 | |
| 85 | if not valid: |
| 86 | continue |
| 87 | |
| 88 | # Check if equation is satisfied |
| 89 | if sum(addend_values) == result_value: |
| 90 | return mapping |
| 91 | |
| 92 | # Edge Case: No solution found |
| 93 | return None |
| 94 | |
| 95 | # Handled Edge Cases: Invalid puzzle format, No letters in puzzle, More than 10 unique letters, Leading zero, No solution found |