CODE-0004 · grok-4.5 (high)def int_to_roman(n):
if type(n) is not int or n < 1 or n > 3999:
raise ValueError("n must be an integer in the range 1..3999")
pairs = (
(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"),
)
parts = []
for value, symbol in pairs:
count, n = divmod(n, value)
if count:
parts.append(symbol * count)
return "".join(parts)
def roman_to_int(s):
if type(s) is not str or not s:
raise ValueError("s must be a non-empty canonical Roman numeral string")
values = {
"I": 1,
"V": 5,
"X": 10,
"L": 50,
"C": 100,
"D": 500,
"M": 1000,
}
for ch in s:
if ch not in values:
raise ValueError("s must be a non-empty canonical Roman numeral string")
total = 0
i = 0
length = len(s)
while i < length:
if i + 1 < length and values[s[i]] < values[s[i + 1]]:
total += values[s[i + 1]] - values[s[i]]
i += 2
else:
total += values[s[i]]
i += 1
if total < 1 or total > 3999 or int_to_roman(total) != s:
raise ValueError("s must be a non-empty canonical Roman numeral string")
return total