relax

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: Invalid puzzle format
20 if "==" not in puzzle:
21 return None
22
23 left_side, right_side = puzzle.replace(" ", "").split("==")
24
25 # Edge Case: Empty sides
26 if not left_side or not right_side:
27 return None
28
29 # Handle addition specifically
30 addends = left_side.split("+")
31
32 # Edge Case: No addends
33 if not addends or any(not addend for addend in addends):
34 return None
35
36 # Get all unique letters
37 letters = set("".join(addends) + right_side)
38
39 # Edge Case: More than 10 unique letters (impossible to solve)
40 if len(letters) > 10:
41 return None
42
43 # Get first letters (can't be zero)
44 first_letters = {word[0] for word in addends + [right_side]}
45
46 # Edge Case: First letters include non-alphabetic characters
47 if any(not letter.isalpha() for letter in first_letters):
48 return None
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 # Skip if any first letter is mapped to zero
56 # Edge Case: Leading digit is zero
57 if any(mapping[letter] == 0 for letter in first_letters):
58 continue
59
60 # Convert words to numbers
61 try:
62 addend_values = [int("".join(str(mapping[c]) for c in addend)) for addend in addends]
63 result_value = int("".join(str(mapping[c]) for c in right_side))
64 except (KeyError, ValueError):
65 # Edge Case: Non-letter characters in words
66 continue
67
68 # Check if the equation is satisfied
69 if sum(addend_values) == result_value:
70 return mapping
71
72 # Edge Case: No solution found
73 return None
74# Handled Edge Cases: Invalid puzzle format, Empty sides, No addends, More than 10 unique letters, Leading digit is zero, Non-letter characters in words, 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.