| 1 | import itertools |
| 2 | import re |
| 3 | |
| 1 | 4 | def solve(puzzle: str) -> dict[str, int] | None: |
| 2 | | pass |
| 5 | # Edge Case: Empty or None puzzle |
| 6 | if not puzzle: |
| 7 | return None |
| 8 | |
| 9 | # Parse the puzzle into words |
| 10 | # Remove spaces and split by '==' and '+' |
| 11 | puzzle = puzzle.replace(" ", "") |
| 12 | if "==" not in puzzle: |
| 13 | return None |
| 14 | |
| 15 | left_right = puzzle.split("==") |
| 16 | if len(left_right) != 2: |
| 17 | return None |
| 18 | |
| 19 | left_side = left_right[0] |
| 20 | right_side = left_right[1] |
| 21 | |
| 22 | # Split left side by '+' |
| 23 | addends = left_side.split("+") |
| 24 | result = right_side |
| 25 | |
| 26 | # Edge Case: No addends or no result |
| 27 | if not addends or not result: |
| 28 | return None |
| 29 | |
| 30 | # Extract all unique letters |
| 31 | letters = set(re.findall(r'[A-Z]', puzzle)) |
| 32 | |
| 33 | # Edge Case: No letters in puzzle |
| 34 | if not letters: |
| 35 | return None |
| 36 | |
| 37 | # Extract first letters of each word (cannot be zero) |
| 38 | first_letters = {word[0] for word in addends + [result]} |
| 39 | |
| 40 | # Edge Case: More than 10 unique letters (impossible to assign unique digits) |
| 41 | if len(letters) > 10: |
| 42 | return None |
| 43 | |
| 44 | # Generate all possible digit permutations for the letters |
| 45 | digits = range(10) |
| 46 | for perm in itertools.permutations(digits, len(letters)): |
| 47 | mapping = dict(zip(letters, perm)) |
| 48 | |
| 49 | # Edge Case: Leading zero in any word |
| 50 | if any(mapping[word[0]] == 0 for word in addends + [result]): |
| 51 | continue |
| 52 | |
| 53 | # Convert words to numbers using the current mapping |
| 54 | try: |
| 55 | addend_values = [int(''.join(str(mapping[c]) for c in word)) for word in addends] |
| 56 | result_value = int(''.join(str(mapping[c]) for c in result)) |
| 57 | except KeyError: |
| 58 | # Edge Case: Mapping is incomplete (should not happen with correct permutation logic) |
| 59 | continue |
| 60 | |
| 61 | # Check if the sum is correct |
| 62 | if sum(addend_values) == result_value: |
| 63 | return mapping |
| 64 | |
| 65 | # Edge Case: No valid solution found |
| 66 | return None |
| 67 | # Handled Edge Cases: Empty or None puzzle, No '==' in puzzle, Incorrect number of sides, No addends or no result, No letters in puzzle, More than 10 unique letters, Leading zero in any word, Mapping is incomplete, No valid solution found |