Alone

Finished
1from itertools import permutations
2
13def 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 Example:
14 >>> solve("SEND + MORE == MONEY")
15 {'S': 9, 'E': 5, 'N': 6, 'D': 7, 'M': 1, 'O': 0, 'R': 8, 'Y': 2}
16 """
17 # Parse the puzzle
18 # Edge Case: Invalid puzzle format
19 if "==" not in puzzle:
20 return None
21
22 left_side, right_side = puzzle.replace(" ", "").split("==")
23
24 # Edge Case: Empty sides
25 if not left_side or not right_side:
26 return None
27
28 # Split the left side by '+' to get the addends
29 addends = left_side.split("+")
30
31 # Edge Case: No addends
32 if not addends:
33 return None
34
35 # Get all unique letters in the puzzle
36 letters = set("".join(addends) + right_side)
37
38 # Edge Case: More than 10 unique letters (impossible to assign unique digits)
39 if len(letters) > 10:
40 return None
41
42 # Get the first letter of each word (these can't be zero)
43 first_letters = {word[0] for word in addends + [right_side]}
44
45 # Try all possible digit assignments
46 for perm in permutations(range(10), len(letters)):
47 mapping = dict(zip(letters, perm))
48
49 # Edge Case: Leading zero
50 if any(mapping[letter] == 0 for letter in first_letters):
51 continue
52
53 # Convert words to numbers using the current mapping
54 try:
55 addend_values = [int("".join(str(mapping[c]) for c in word)) for word in addends]
56 result_value = int("".join(str(mapping[c]) for c in right_side))
57 except KeyError:
58 # This shouldn't happen with our approach, but just in case
59 continue
60
61 # Check if the sum is correct
62 if sum(addend_values) == result_value:
63 return mapping
64
65 # Edge Case: No solution found
66 return None
67 # 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.