Computer >> Computer tutorials >  >> Programming >> Python

Program to convert integer to roman numeral in Python


Suppose we have a number num. We have to convert it into its equivalent roman numeral. Roman numerals contain the symbols and values like below −

  • "I" = 1
  • "V" = 5
  • "X" = 10
  • "L" = 50
  • "C" = 100
  • "D" = 500
  • "M" = 1000

These symbols are typically written largest to smallest, and from left to right order, and can be computed by summing the values of all the symbols. But there are some special cases, where a symbol of lower value is to the left of a symbol of higher value, his indicates the lower value is subtracted from the higher one.

These are examples of such cases −

  • "I" is before "V", value 4.
  • "I" is before "X", value 9.
  • "X" is before "L", value 40.
  • "X" is before "C", value 90.
  • "C" is before "D", value 400.
  • "C" is before "M", value 900.

In Roman numerals there are also few rules −

  • No symbol is repeated more than 3 times.
  • The symbols "V", "L", and "D" are not repeated.

So, if the input is like n = 1520, then the output will be "MDXX", because "MDXX" indicates 1000 + 500 + 10 + 10 = 1520.

To solve this, we will follow these steps −

  • res := blank string
  • table = a list containing pairs (val, symbol) in this format, where val is the value and symbol is the associated symbol [(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")]
  • for each pair (cap, roman) in table, do
    • d := floor of num/cap
    • m := num mod cap
    • res := res + roman * d
    • num := m
  • return res

Example

Let us see the following implementation to get better understanding −

def solve(num):
   res = ""
   table = [
      (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"),
   ]
   for cap, roman in table:
      d, m = divmod(num, cap)
      res += roman * d
      num = m

   return res

num = 1520
print(solve(num))

Input

1520

Output

MDXX