bohdan

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 # Edge Case: Empty or None puzzle
16 if not puzzle:
17 return None
18
19 # Parse the puzzle
20 parts = puzzle.replace("==", "=").replace(" ", "").split("=")
21
22 # Edge Case: Invalid puzzle format (no equals sign or too many parts)
23 if len(parts) != 2:
24 return None
25
26 right_side = parts[1]
27 left_parts = parts[0].replace("+", " ").split()
28
29 # Edge Case: No terms on the left side
30 if not left_parts:
31 return None
32
33 # Extract all unique letters
34 letters = set()
35 for part in left_parts + [right_side]:
36 letters.update(part)
37
38 # Edge Case: No letters in puzzle
39 if not letters:
40 return None
41
42 # Extract first letters (can't be zero)
43 first_letters = {word[0] for word in left_parts + [right_side]}
44
45 # Convert letters to a sorted list for consistent ordering
46 letters = list(letters)
47
48 # Try all possible digit assignments
49 from itertools import permutations
50
51 # Edge Case: More unique letters than digits (0-9)
52 if len(letters) > 10:
53 return None
54
55 # Try all permutations of digits for the letters
56 for perm in permutations(range(10), len(letters)):
57 mapping = dict(zip(letters, perm))
58
59 # Edge Case: Leading zero in any number
60 if any(mapping[first_letter] == 0 for first_letter in first_letters):
61 continue
62
63 # Calculate the values of the left side terms
64 left_values = []
65 for word in left_parts:
66 value = 0
67 for char in word:
68 value = value * 10 + mapping[char]
69 left_values.append(value)
70
71 # Calculate the value of the right side
72 right_value = 0
73 for char in right_side:
74 right_value = right_value * 10 + mapping[char]
75
76 # Check if the equation is satisfied
77 if sum(left_values) == right_value:
78 return mapping
79
80 # Edge Case: No valid solution found
81 return None
82
83# Handled Edge Cases: Empty or None puzzle, Invalid puzzle format, No terms on left side, No letters in puzzle, More unique letters than digits, Leading zero in any number, No 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.