joseph

Finished
1import itertools
2import re
3
14def solve(puzzle: str) -> dict[str, int] | None:
2 pass
5 # Edge Case: Empty or None puzzle
6 if not puzzle:
7 return None
8
9 # Parse the puzzle into words
10 # The puzzle is expected to be in the format "A + B == C" or similar
11 # We extract all uppercase words (potential alphametic words)
12 words = re.findall(r'[A-Z]+', puzzle)
13
14 # Check if this is an addition puzzle (contains + and ==)
15 if '+' not in puzzle or '==' not in puzzle:
16 # For now, we only support addition puzzles
17 return None
18
19 # Edge Case: No words found in puzzle
20 if not words:
21 return None
22
23 # The last word is the result, the rest are addends
24 addends = words[:-1]
25 result = words[-1]
26
27 # Edge Case: No addends (e.g., just "A == BC")
28 if not addends:
29 return None
30
31 # Get all unique letters
32 unique_letters = set(''.join(words))
33
34 # Edge Case: More than 10 unique letters (impossible to solve with digits 0-9)
35 if len(unique_letters) > 10:
36 return None
37
38 # Get first letters of each word (cannot be zero)
39 first_letters = {word[0] for word in words}
40
41 # Generate all possible digit assignments
42 digits = range(10)
43
44 # Convert unique_letters to a list for consistent ordering
45 unique_letters_list = list(unique_letters)
46
47 # Try all permutations of digits for the unique letters
48 for perm in itertools.permutations(digits, len(unique_letters_list)):
49 # Create a mapping from letters to digits
50 mapping = dict(zip(unique_letters_list, perm))
51
52 # Edge Case: Leading digit is zero
53 if any(mapping[letter] == 0 for letter in first_letters):
54 continue
55
56 # Convert words to numbers using the mapping
57 def word_to_number(word):
58 return int(''.join(str(mapping[letter]) for letter in word))
59
60 # Calculate the sum of addends
61 addend_sum = sum(word_to_number(addend) for addend in addends)
62
63 # Calculate the result value
64 result_value = word_to_number(result)
65
66 # Check if the equation is satisfied
67 if addend_sum == result_value:
68 return mapping
69
70 # Edge Case: No solution found
71 return None
72# Handled Edge Cases: Empty or None puzzle, No words found in puzzle, No addends, More than 10 unique letters, Leading digit is 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.