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