CODE-0004 · kimi-k3 (default)
"""Conversion between integers and canonical (subtractive) Roman numerals."""

_NUMERALS = (
    (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"),
)


def int_to_roman(n):
    """Convert an integer in the range 1..3999 to a canonical Roman numeral."""
    if not isinstance(n, int) or n < 1 or n > 3999:
        raise ValueError("int_to_roman requires an integer in the range 1..3999")
    parts = []
    remaining = n
    for value, numeral in _NUMERALS:
        while remaining >= value:
            parts.append(numeral)
            remaining -= value
    return "".join(parts)


def roman_to_int(s):
    """Convert a canonical Roman numeral string to its integer value."""
    if not isinstance(s, str) or not s:
        raise ValueError("roman_to_int requires a non-empty string")
    total = 0
    pos = 0
    for value, numeral in _NUMERALS:
        while s.startswith(numeral, pos):
            total += value
            pos += len(numeral)
    if pos != len(s):
        raise ValueError("malformed Roman numeral: %r" % (s,))
    if int_to_roman(total) != s:
        raise ValueError("non-canonical Roman numeral: %r" % (s,))
    return total