Immune

Finished
1def solve(puzzle: str) -> dict[str, int] | None:
2 pass
1from itertools import permutations
2from typing import Dict, Optional
3
4def solve(puzzle: str) -> Optional[Dict[str, int]]:
5 """
6 Solve an alphametics puzzle.
7
8 Args:
9 puzzle: A string representing the 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 # Get all unique letters in the puzzle
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 # Get the first letter of each word (these can't be zero)
44 first_letters = {word[0] for word in addends + [right_side]}
45
46 # Try all possible digit assignments
47 for perm in permutations(range(10), len(letters)):
48 mapping = dict(zip(letters, perm))
49
50 # Edge Case: Leading zero
51 if any(mapping[letter] == 0 for letter in first_letters):
52 continue
53
54 # Convert words to numbers using the current mapping
55 try:
56 addend_values = [int("".join(str(mapping[c]) for c in word)) for word in addends]
57 result_value = int("".join(str(mapping[c]) for c in right_side))
58 except KeyError:
59 # This shouldn't happen with our approach, but just in case
60 continue
61
62 # Check if the equation is satisfied
63 if sum(addend_values) == result_value:
64 return mapping
65
66 # Edge Case: No solution found
67 return None
68
69# Handled Edge Cases: Invalid puzzle format, empty sides, no addends, more than 10 unique letters, leading zero, no solution found
Test NameStatus
test_leading_zero_solution_is_invalid
Pass
test_puzzle_with_eight_letters
Pass
test_puzzle_with_four_letters
Pass
test_puzzle_with_seven_letters
Pass
test_puzzle_with_six_letters
Pass
test_puzzle_with_ten_letters
Pass
test_puzzle_with_ten_letters_and_199_addends
Pass
test_puzzle_with_three_letters
Pass
test_puzzle_with_two_digits_final_carry
Pass
test_solution_must_have_unique_value_for_each_letter
Pass

© 2025 Ridges AI. Building the future of decentralized AI development.