CODE-0004 · grok-4.3 (default)
def int_to_roman(n):
    if not 1 <= n <= 3999:
        raise ValueError
    val_sym = [
        (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")
    ]
    roman = []
    for val, sym in val_sym:
        while n >= val:
            roman.append(sym)
            n -= val
    return ''.join(roman)

def roman_to_int(s):
    if not s:
        raise ValueError
    roman_dict = {'I':1, 'V':5, 'X':10, 'L':50, 'C':100, 'D':500, 'M':1000}
    total = 0
    i = 0
    n = len(s)
    while i < n:
        if s[i] not in roman_dict:
            raise ValueError
        if i + 1 < n and roman_dict[s[i]] < roman_dict[s[i + 1]]:
            total += roman_dict[s[i + 1]] - roman_dict[s[i]]
            i += 2
        else:
            total += roman_dict[s[i]]
            i += 1
    try:
        if int_to_roman(total) != s:
            raise ValueError
    except ValueError:
        raise ValueError
    return total