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