CODE-0004 · claude-haiku-4-5 (high)Perfect! All tests pass. Now let me output the solution file as required:
def int_to_roman(n):
"""
Convert an integer in the range 1..3999 to its canonical Roman numeral string.
Uses subtractive notation: IV, IX, XL, XC, CD, CM.
Raises ValueError for integers outside 1..3999.
"""
if not isinstance(n, int) or n < 1 or n > 3999:
raise ValueError(f"Integer must be in range 1..3999, got {n}")
# Mapping of values to Roman numerals in descending order
# Includes both base symbols and subtractive forms
val_to_roman = [
(1000, 'M'),
(900, 'CM'),
(500, 'D'),
(400, 'CD'),
(100, 'C'),
(90, 'XC'),
(50, 'L'),
(40, 'XL'),
(10, 'X'),
(9, 'IX'),
(5, 'V'),
(4, 'IV'),
(1, 'I'),
]
result = []
for value, roman in val_to_roman:
count = n // value
if count:
result.append(roman * count)
n -= value * count
return ''.join(result)
def roman_to_int(s):
"""
Convert a canonical Roman numeral string to its integer value.
Raises ValueError for empty strings, malformed, or non-canonical numerals.
"""
if not s:
raise ValueError("Empty string is not a valid Roman numeral")
# Mapping of Roman numeral characters to their values
roman_values = {
'I': 1,
'V': 5,
'X': 10,
'L': 50,
'C': 100,
'D': 500,
'M': 1000,
}
# Check all characters are valid
for char in s:
if char not in roman_values:
raise ValueError(f"Invalid character '{char}' in Roman numeral: {s}")
# Valid subtractive pairs in canonical notation
valid_subtractive = {
'IV', 'IX',
'XL', 'XC',
'CD', 'CM',
}
result = 0
i = 0
while i < len(s):
# Check if current character and next character form a valid subtractive pair
if i + 1 < len(s):
two_char = s[i:i+2]
if two_char in valid_subtractive:
result += roman_values[s[i+1]] - roman_values[s[i]]
i += 2
continue
# Single character (not part of a subtractive pair)
result += roman_values[s[i]]
i += 1
# Verify the result is canonical by converting back
# If the round-trip doesn't match, the input was non-canonical
if int_to_roman(result) != s:
raise ValueError(f"Non-canonical or malformed Roman numeral: {s}")
return result