| 1 | from itertools import permutations |
| 2 | |
| 3 | |
| 1 | 4 | def solve(puzzle: str) -> dict[str, int] | None: |
| 2 | | pass |
| 5 | """ |
| 6 | Solve an alphametics puzzle. |
| 7 | |
| 8 | Args: |
| 9 | puzzle (str): A string representing the alphametics puzzle (e.g., "SEND + MORE == MONEY") |
| 10 | |
| 11 | Returns: |
| 12 | dict[str, int] | None: A dictionary mapping letters to digits if a solution is found, otherwise None |
| 13 | |
| 14 | Example: |
| 15 | >>> solve("SEND + MORE == MONEY") |
| 16 | {'S': 9, 'E': 5, 'N': 6, 'D': 7, 'M': 1, 'O': 0, 'R': 8, 'Y': 2} |
| 17 | """ |
| 18 | # Edge Case: Empty or None puzzle |
| 19 | if not puzzle: |
| 20 | return None |
| 21 | |
| 22 | # Parse the puzzle into parts |
| 23 | parts = puzzle.replace("==", "=").replace(" ", "").split("=") |
| 24 | |
| 25 | # Edge Case: Invalid puzzle format (no equals sign or too many parts) |
| 26 | if len(parts) != 2: |
| 27 | return None |
| 28 | |
| 29 | right_side = parts[1] |
| 30 | left_parts = parts[0].replace("+", " ").split() |
| 31 | |
| 32 | # Edge Case: No terms on the left side |
| 33 | if not left_parts: |
| 34 | return None |
| 35 | |
| 36 | # Extract all unique letters |
| 37 | letters = set(ch for ch in puzzle if ch.isalpha()) |
| 38 | |
| 39 | # Edge Case: No letters in puzzle |
| 40 | if not letters: |
| 41 | return None |
| 42 | |
| 43 | # Identify first letters (can't be zero) |
| 44 | first_letters = {word[0] for word in left_parts + [right_side] if len(word) > 1} |
| 45 | |
| 46 | # Edge Case: Single character words that are first letters |
| 47 | # This is handled by the first_letters set logic above |
| 48 | |
| 49 | # Get sorted list of unique letters for consistent mapping |
| 50 | sorted_letters = sorted(letters) |
| 51 | |
| 52 | # Try all digit permutations for the unique letters |
| 53 | for perm in permutations(range(10), len(letters)): |
| 54 | mapping = dict(zip(sorted_letters, perm)) |
| 55 | |
| 56 | # Edge Case: Leading zero in any multi-digit number |
| 57 | if any(mapping[letter] == 0 for letter in first_letters): |
| 58 | continue |
| 59 | |
| 60 | # Convert words to numbers using the current mapping |
| 61 | left_values = [] |
| 62 | for word in left_parts: |
| 63 | value = 0 |
| 64 | for ch in word: |
| 65 | value = value * 10 + mapping[ch] |
| 66 | left_values.append(value) |
| 67 | |
| 68 | right_value = 0 |
| 69 | for ch in right_side: |
| 70 | right_value = right_value * 10 + mapping[ch] |
| 71 | |
| 72 | # Check if the equation is satisfied |
| 73 | if sum(left_values) == right_value: |
| 74 | return mapping |
| 75 | |
| 76 | # Edge Case: No valid solution found |
| 77 | return None |
| 78 | # Handled Edge Cases: Empty or None puzzle, Invalid puzzle format, No terms on the left side, No letters in puzzle, Leading zero in any multi-digit number, No valid solution found |