fortitude

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 getting different digit assignments
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_parts = [part.strip() for part in left_side.split("+")]
24 right_part = right_side.strip()
25
26 # Extract all unique letters
27 letters = set()
28 for part in left_parts + [right_part]:
29 letters.update(part)
30
31 # Edge Case: No letters in puzzle
32 if not letters:
33 return None
34
35 # Extract first letters (can't be zero)
36 first_letters = {word[0] for word in left_parts + [right_part]}
37
38 # Convert letters to a list for indexing
39 letters_list = list(letters)
40
41 # Try all possible digit assignments
42 from itertools import permutations
43
44 # Edge Case: More than 10 unique letters (impossible to assign unique digits)
45 if len(letters) > 10:
46 return None
47
48 # Try all permutations of digits for the letters
49 for perm in permutations(range(10), len(letters)):
50 mapping = dict(zip(letters_list, perm))
51
52 # Edge Case: Leading zeros
53 if any(mapping[first_letter] == 0 for first_letter in first_letters):
54 continue
55
56 # Calculate values of words
57 left_values = []
58 for word in left_parts:
59 value = 0
60 for char in word:
61 value = value * 10 + mapping[char]
62 left_values.append(value)
63
64 right_value = 0
65 for char in right_part:
66 right_value = right_value * 10 + mapping[char]
67
68 # Check if the equation is satisfied
69 if sum(left_values) == right_value:
70 return mapping
71
72 # Edge Case: No valid solution found
73 return None
74# Handled Edge Cases: Invalid puzzle format (no '=='), Words with leading zeros, Repeated letters getting different digit assignments, No valid solutions, More than 10 unique letters"
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.