| 1 | | def solve(puzzle: str) -> dict[str, int] | None: |
| 2 | | pass |
| 1 | from itertools import permutations |
| 2 | from typing import Dict, Optional |
| 3 | |
| 4 | def solve(puzzle: str) -> Optional[Dict[str, int]]: |
| 5 | """ |
| 6 | Solve an alphametics puzzle. |
| 7 | |
| 8 | Args: |
| 9 | puzzle: A string representing an alphametics puzzle (e.g., "SEND + MORE == MONEY") |
| 10 | |
| 11 | Returns: |
| 12 | A dictionary mapping letters to digits that solves the puzzle, or None if no solution exists. |
| 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 | # Parse the puzzle |
| 19 | # Edge Case: Invalid puzzle format |
| 20 | if '==' not in puzzle: |
| 21 | return None |
| 22 | |
| 23 | left_side, right_side = puzzle.replace(' ', '').split('==') |
| 24 | |
| 25 | # Edge Case: Empty sides |
| 26 | if not left_side or not right_side: |
| 27 | return None |
| 28 | |
| 29 | # Split the left side by '+' to get addends |
| 30 | addends = left_side.split('+') |
| 31 | |
| 32 | # Edge Case: No addends |
| 33 | if not addends: |
| 34 | return None |
| 35 | |
| 36 | # Extract all unique letters |
| 37 | letters = set(''.join(addends) + right_side) |
| 38 | |
| 39 | # Edge Case: More than 10 unique letters (impossible to assign unique digits) |
| 40 | if len(letters) > 10: |
| 41 | return None |
| 42 | |
| 43 | # Identify first letters (can't be zero) |
| 44 | first_letters = {word[0] for word in addends + [right_side]} |
| 45 | |
| 46 | # Edge Case: First letters include non-alphabetic characters |
| 47 | if any(not c.isalpha() for c in first_letters): |
| 48 | return None |
| 49 | |
| 50 | # Try all digit permutations for the letters |
| 51 | for perm in permutations(range(10), len(letters)): |
| 52 | mapping = dict(zip(letters, perm)) |
| 53 | |
| 54 | # Edge Case: Leading zero in any word |
| 55 | if any(mapping.get(letter) == 0 for letter in first_letters): |
| 56 | continue |
| 57 | |
| 58 | # Convert words to numbers |
| 59 | try: |
| 60 | addend_values = [] |
| 61 | for addend in addends: |
| 62 | value = 0 |
| 63 | for letter in addend: |
| 64 | value = value * 10 + mapping[letter] |
| 65 | addend_values.append(value) |
| 66 | |
| 67 | result_value = 0 |
| 68 | for letter in right_side: |
| 69 | result_value = result_value * 10 + mapping[letter] |
| 70 | except KeyError: |
| 71 | # Edge Case: Non-alphabetic characters in words |
| 72 | continue |
| 73 | |
| 74 | # Check if the equation is satisfied |
| 75 | if sum(addend_values) == result_value: |
| 76 | return mapping |
| 77 | |
| 78 | # Edge Case: No valid solution found |
| 79 | return None |
| 80 | |
| 81 | # Handled Edge Cases: Invalid puzzle format, empty sides, no addends, more than 10 unique letters, |
| 82 | # leading zero in any word, non-alphabetic characters in words, no valid solution found |