xas

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 The function handles the following edge cases:
12 - Invalid puzzle format (no '==')
13 - Words with leading zeros
14 - Repeated letters in the mapping
15 - No valid solutions
16 """
17 # Edge Case: Invalid puzzle format (no '==')
18 if "==" not in puzzle:
19 return None
20
21 # Parse the puzzle
22 left_side, right_side = puzzle.split("==")
23 left_side = left_side.strip()
24 right_side = right_side.strip()
25
26 # Extract words (remove operators like +, -)
27 import re
28 addends = re.findall(r'[A-Z]+', left_side)
29 result_word = right_side
30
31 # Edge Case: No words found
32 if not addends or not result_word:
33 return None
34
35 # Get all unique letters
36 all_words = addends + [result_word]
37 unique_letters = set(''.join(all_words))
38
39 # Edge Case: More than 10 unique letters (impossible to assign unique digits)
40 if len(unique_letters) > 10:
41 return None
42
43 # Get first letters of each word (can't be zero)
44 first_letters = {word[0] for word in all_words}
45
46 # Generate all possible digit assignments
47 from itertools import permutations
48
49 # Try all permutations of digits for the unique letters
50 for perm in permutations(range(10), len(unique_letters)):
51 mapping = dict(zip(unique_letters, perm))
52
53 # Edge Case: Leading zero in any word
54 if any(mapping[word[0]] == 0 for word in all_words):
55 continue
56
57 # Convert addends to numbers using the mapping
58 addend_numbers = []
59 for word in addends:
60 num = 0
61 for char in word:
62 num = num * 10 + mapping[char]
63 addend_numbers.append(num)
64
65 # Convert result to number
66 result_number = 0
67 for char in result_word:
68 result_number = result_number * 10 + mapping[char]
69
70 # Check if the equation holds
71 if sum(addend_numbers) == result_number:
72 return mapping
73
74 # Edge Case: No valid solution found
75 return None
76# Handled Edge Cases: Invalid puzzle format (no '=='), No words found, More than 10 unique letters, 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.