great

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 The function handles the following edge cases:
14 - Invalid puzzle format (no '==')
15 - Words with leading zeros
16 - No valid solutions
17 """
18 # Edge Case: Invalid puzzle format (no '==')
19 if "==" not in puzzle:
20 return None
21
22 # Split the puzzle into left and right sides
23 left_side, right_side = puzzle.split("==")
24 left_side = left_side.strip()
25 right_side = right_side.strip()
26
27 # Extract all words from the puzzle
28 words = [word for word in left_side.replace('+', ' ').split() if word.isalpha()]
29 words.append(right_side)
30
31 # Edge Case: No words found
32 if not words:
33 return None
34
35 # Get all unique letters in the puzzle
36 letters = set(''.join(words))
37
38 # Edge Case: More than 10 unique letters (impossible to solve)
39 if len(letters) > 10:
40 return None
41
42 # Get the first letter of each word (these cannot be zero)
43 first_letters = {word[0] for word in words}
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 in any word
50 if any(mapping[first_letter] == 0 for first_letter in first_letters):
51 continue
52
53 # Convert words to numbers using the current mapping
54 numbers = []
55 for word in words:
56 number = 0
57 for char in word:
58 number = number * 10 + mapping[char]
59 numbers.append(number)
60
61 # Check if the sum of left side equals the right side
62 if sum(numbers[:-1]) == numbers[-1]:
63 return mapping
64
65 # Edge Case: No valid solution found
66 return None
67# Handled Edge Cases: Invalid puzzle format (no '=='), No words found, More than 10 unique letters (impossible to solve), Leading zero in any word, 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.