| 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 | The function handles the following edge cases: |
| 14 | - Invalid puzzle format (no '==') |
| 15 | - Words with leading zeros |
| 16 | - No valid solutions |
| 17 | """ |
| 18 | # Edge Case: Invalid puzzle format (no '==') |
| 19 | if "==" not in puzzle: |
| 20 | return None |
| 21 | |
| 22 | # Convert to uppercase for case insensitivity |
| 23 | puzzle = puzzle.upper() |
| 24 | |
| 25 | # Split the puzzle into left and right sides |
| 26 | left_side, right_side = puzzle.split("==") |
| 27 | left_side = left_side.strip() |
| 28 | right_side = right_side.strip() |
| 29 | |
| 30 | # Extract all words from the puzzle |
| 31 | words = [word for word in left_side.replace('+', ' ').split() if word.isalpha()] + [right_side] |
| 32 | |
| 33 | # Edge Case: No words in puzzle |
| 34 | if not words: |
| 35 | return None |
| 36 | |
| 37 | # Get all unique letters in the puzzle |
| 38 | unique_letters = set(''.join(words)) |
| 39 | |
| 40 | # Edge Case: More than 10 unique letters (impossible to solve) |
| 41 | if len(unique_letters) > 10: |
| 42 | return None |
| 43 | |
| 44 | # Get the first letter of each word (these cannot be zero) |
| 45 | first_letters = {word[0] for word in words} |
| 46 | |
| 47 | # Try all possible digit assignments |
| 48 | for perm in permutations(range(10), len(unique_letters)): |
| 49 | mapping = dict(zip(unique_letters, perm)) |
| 50 | |
| 51 | # Edge Case: Leading zero in any word |
| 52 | if any(mapping[word[0]] == 0 for word in words): |
| 53 | continue |
| 54 | |
| 55 | # Convert words to numbers using the current mapping |
| 56 | numbers = [] |
| 57 | for word in words: |
| 58 | number = 0 |
| 59 | for letter in word: |
| 60 | number = number * 10 + mapping[letter] |
| 61 | numbers.append(number) |
| 62 | |
| 63 | # Check if the sum of left side equals the right side |
| 64 | if sum(numbers[:-1]) == numbers[-1]: |
| 65 | return mapping |
| 66 | |
| 67 | # Edge Case: No valid solution found |
| 68 | return None |
| 69 | # Handled Edge Cases: Invalid puzzle format (no '=='), No words in puzzle, More than 10 unique letters (impossible to solve), Leading zero in any word, No valid solution found |