rockstar

Finished
11def solve(puzzle: str) -> dict[str, int] | None:
2 pass
2 """
3 Solve an alphametics puzzle.
4
5 Args:
6 puzzle: A string representing the alphametics puzzle (e.g., "SEND + MORE == MONEY")
7
8 Returns:
9 A dictionary mapping letters to digits that solves the puzzle, or None if no solution exists.
10
11 Example:
12 >>> solve("SEND + MORE == MONEY")
13 {'S': 9, 'E': 5, 'N': 6, 'D': 7, 'M': 1, 'O': 0, 'R': 8, 'Y': 2}
14 """
15 # Parse the puzzle
16 if "==" not in puzzle:
17 return None
18
19 left_side, right_side = puzzle.split("==")
20 left_side = left_side.strip()
21 right_side = right_side.strip()
22
23 # Extract words (remove operators and spaces)
24 words = []
25 for part in left_side.split("+"):
26 words.append(part.strip())
27 words.append(right_side)
28
29 # Edge Case: Empty puzzle or invalid format
30 if not all(words):
31 return None
32
33 # Get all unique letters
34 letters = set()
35 for word in words:
36 letters.update(word)
37
38 # Edge Case: More than 10 unique letters (impossible to solve)
39 if len(letters) > 10:
40 return None
41
42 first_letters = {word[0] for word in words}
43
44 # Edge Case: Empty letters set
45 if not letters:
46 return None
47
48 letters = list(letters)
49
50 # Try all possible digit assignments
51 from itertools import permutations
52
53 # Edge Case: Not enough digits for letters
54 for perm in permutations(range(10), len(letters)):
55 mapping = dict(zip(letters, perm))
56
57 # Edge Case: Leading zero
58 if any(mapping[first_letter] == 0 for first_letter in first_letters):
59 continue
60
61 # Calculate values of words
62 try:
63 left_value = 0
64 for word in words[:-1]: # All words except the last (result)
65 num = 0
66 for char in word:
67 num = num * 10 + mapping[char]
68 left_value += num
69
70 right_value = 0
71 for char in words[-1]: # Last word (result)
72 right_value = right_value * 10 + mapping[char]
73
74 # Edge Case: Valid solution found
75 if left_value == right_value:
76 return mapping
77 except KeyError:
78 # Edge Case: Invalid mapping (should not happen with proper permutation)
79 continue
80
81 # Edge Case: No solution found
82 return None
83
84# Handled Edge Cases: Empty puzzle or invalid format, more than 10 unique letters, empty letters set, leading zero, not enough digits for letters, invalid mapping, no solution found, valid 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.