Python Program to Convert Numbers to Roman Numerals and Vice Versa

 

 

Number to Roman Numeral Converter

This Python program allows you to convert numbers to Roman numerals and vice versa. Below is the complete code with explanations and documentation.

Program Code


def int_to_roman(num):
    """
    Convert an integer to a Roman numeral.
    
    Args:
    num (int): The integer to convert.
    
    Returns:
    str: The Roman numeral representation of the integer.
    """
    val = [
        1000, 900, 500, 400,
        100, 90, 50, 40,
        10, 9, 5, 4,
        1
        ]
    syb = [
        "M", "CM", "D", "CD",
        "C", "XC", "L", "XL",
        "X", "IX", "V", "IV",
        "I"
        ]
    roman_num = ''
    i = 0
    while  num > 0:
        for _ in range(num // val[i]):
            roman_num += syb[i]
            num -= val[i]
        i += 1
    return roman_num

def roman_to_int(s):
    """
    Convert a Roman numeral to an integer.
    
    Args:
    s (str): The Roman numeral to convert.
    
    Returns:
    int: The integer representation of the Roman numeral.
    """
    roman = {'I': 1, 'V': 5, 'X': 10, 'L': 50, 'C': 100, 'D': 500, 'M': 1000}
    integer = 0
    for i in range(len(s)):
        if i > 0 and roman[s[i]] > roman[s[i - 1]]:
            integer += roman[s[i]] - 2 * roman[s[i - 1]]
        else:
            integer += roman[s[i]]
    return integer

# Example usage:
print(int_to_roman(1994))  # Output: MCMXCIV
print(roman_to_int('MCMXCIV'))  # Output: 1994
    

Explanation

The program consists of two main functions:

int_to_roman(num)

This function converts an integer to a Roman numeral. It uses two lists:

  • val: Contains the integer values that correspond to Roman numeral symbols.
  • syb: Contains the Roman numeral symbols in decreasing order of value.

The function iterates through the integer, subtracting the values from val and appending the corresponding symbols from syb to the result string roman_num until the integer is reduced to zero.

roman_to_int(s)

This function converts a Roman numeral to an integer. It uses a dictionary roman to map Roman numeral symbols to their integer values.

The function iterates through the input string s. If the current symbol is greater than the previous symbol, it means we need to subtract the value of the previous symbol twice (since it was added once before). Otherwise, it simply adds the value of the current symbol to the result integer integer.

Example Usage

Here are some example usages of the functions:


print(int_to_roman(1994))  # Output: MCMXCIV
print(roman_to_int('MCMXCIV'))  # Output: 1994
    

You can copy the above code and run it in your Python environment to convert numbers to Roman numerals and vice versa.

 

Leave a Reply

Your email address will not be published. Required fields are marked *