yahoo

Finished
1def solve(puzzle: str) -> dict[str, int] | None:
2 pass
1from itertools import permutations
2from typing import Dict, Optional
3
4def solve(puzzle: str) -> Optional[Dict[str, int]]:
5 """
6 Solve an alphametics puzzle.
7
8 Args:
9 puzzle: A string representing an alphametics puzzle (e.g., "SEND + MORE == MONEY")
10
11 Returns:
12 A dictionary mapping letters to digits that solves the puzzle, or None if no solution exists.
13
14 Example:
15 >>> solve("SEND + MORE == MONEY")
16 {'S': 9, 'E': 5, 'N': 6, 'D': 7, 'M': 1, 'O': 0, 'R': 8, 'Y': 2}
17 """
18 # Parse the puzzle
19 # Edge Case: Empty or None puzzle
20 if not puzzle:
21 return None
22
23 # Remove spaces and split by '=='
24 parts = puzzle.replace(" ", "").split("==")
25
26 # Edge Case: Invalid puzzle format (no == or too many parts)
27 if len(parts) != 2:
28 return None
29
30 # Split the left side by '+'
31 addends = parts[0].split("+")
32 result = parts[1]
33
34 # Edge Case: No addends
35 if not addends or not result:
36 return None
37
38 # Get all unique letters
39 letters = set()
40 for part in addends + [result]:
41 letters.update(part)
42
43 # Edge Case: More than 10 unique letters (impossible to solve)
44 if len(letters) > 10:
45 return None
46
47 # Get the first letter of each word (can't be zero)
48 first_letters = {word[0] for word in addends + [result]}
49
50 # Try all digit permutations for the letters
51 digits = range(10)
52 for perm in permutations(digits, len(letters)):
53 mapping = dict(zip(letters, perm))
54
55 # Edge Case: Leading zero in any word
56 if any(mapping[word[0]] == 0 for word in addends + [result]):
57 continue
58
59 # Convert words to numbers
60 try:
61 addend_values = []
62 for word in addends:
63 value = 0
64 for char in word:
65 value = value * 10 + mapping[char]
66 addend_values.append(value)
67
68 result_value = 0
69 for char in result:
70 result_value = result_value * 10 + mapping[char]
71
72 # Check if the sum is correct
73 if sum(addend_values) == result_value:
74 return mapping
75 except KeyError:
76 # Edge Case: Invalid mapping (shouldn't happen with permutations but just in case)
77 continue
78
79 # Edge Case: No solution found
80 return None
81
82# Handled Edge Cases: Empty/None puzzle, invalid format, no addends, more than 10 unique letters, leading zeros, no solution found, invalid mapping
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.