| 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 | # Handle single equation (no ==, assume implicit == 0) |
| 9 | parts = puzzle.replace('=', '==').split('==') |
| 10 | if len(parts) != 2: |
| 11 | return None |
| 12 | left_side, right_side = parts[0], parts[1] |
| 13 | else: |
| 14 | parts = puzzle.split('==') |
| 15 | if len(parts) != 2: |
| 16 | return None |
| 17 | left_side, right_side = parts[0], parts[1] |
| 18 | |
| 19 | # Extract all words (sequences of uppercase letters) |
| 20 | words = re.findall(r'[A-Z]+', puzzle) |
| 21 | |
| 22 | # Edge Case: No words found |
| 23 | if not words: |
| 24 | return None |
| 25 | |
| 26 | # Get all unique letters |
| 27 | unique_letters = set(''.join(words)) |
| 28 | |
| 29 | # Edge Case: More than 10 unique letters (impossible to solve) |
| 30 | if len(unique_letters) > 10: |
| 31 | return None |
| 32 | |
| 33 | # Get first letters of each word (cannot be zero) |
| 34 | first_letters = {word[0] for word in words} |
| 35 | |
| 36 | # Edge Case: Empty words |
| 37 | if any(len(word) == 0 for word in words): |
| 38 | return None |
| 39 | |
| 40 | # Try all permutations of digits for the unique letters |
| 41 | for perm in itertools.permutations(range(10), len(unique_letters)): |
| 42 | mapping = dict(zip(unique_letters, perm)) |
| 43 | |
| 44 | # Edge Case: Leading zeros |
| 45 | if any(mapping[letter] == 0 for letter in first_letters): |
| 46 | continue |
| 47 | |
| 48 | # Convert words to numbers using the current mapping |
| 49 | def word_to_number(word): |
| 50 | return int(''.join(str(mapping[letter]) for letter in word)) |
| 51 | |
| 52 | # Evaluate the left side of the equation |
| 53 | try: |
| 54 | # Split left side by '+' and sum |
| 55 | left_parts = left_side.replace(" ", "").split('+') |
| 56 | left_value = sum(word_to_number(part) for part in left_parts if part) |
| 57 | |
| 58 | # Get the right side value |
| 59 | right_value = word_to_number(right_side.replace(" ", "")) |
| 60 | |
| 61 | # Check if the equation is satisfied |
| 62 | if left_value == right_value: |
| 63 | return mapping |
| 64 | except (KeyError, ValueError): |
| 65 | # Edge Case: Invalid mapping or conversion |
| 66 | continue |
| 67 | |
| 68 | # Edge Case: No solution found |
| 69 | return None |
| 70 | # Handled Edge Cases: Invalid puzzle format, No words found, More than 10 unique letters, Empty words, Leading zeros, Invalid mapping or conversion, No solution found |