Advertisement
jasonpogi1669

Convert Number to Roman Numeral and Vice Versa up to 5000 using Python

Oct 9th, 2021 (edited)
80
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 5.78 KB | None | 0 0
  1. #Name: Mark Jason T. Galang
  2. #School: FEU-TECH
  3. #Machine Problem number - 3
  4.  
  5. class RomanNumerals:
  6.   def __init__(self):
  7.     # constructor
  8.     self.res1 = ""
  9.     self.res2 = 0
  10.  
  11.   def convert_to_roman(self, num):
  12.     """
  13.    this function converts an integer to roman numerals
  14.    """
  15.     # roman numeral symbols
  16.     thousands = ["M", "MM", "MMM", "MMMM", "V̅"]
  17.     hundreds = ["C", "CC", "CCC", "CD", "D" ,"DC", "DCC", "DCCC", "CM"]
  18.     tens = ["X", "XX", "XXX", "XL", "L", "LX", "LXX", "LXXX", "XC"]
  19.     ones = ["I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX"]
  20.    
  21.     # conversion using recursion
  22.     # process: divide the number by its place value
  23.     # and store the corresponding roman numeral symbols
  24.     # using the (leading digit - 1) (0-based)
  25.     if num >= 1000:
  26.       self.res1 += thousands[(num // 1000) - 1]
  27.       if num % 1000 != 0:
  28.         return self.convert_to_roman(num % 1000)
  29.       else:
  30.         return self.res1
  31.     elif num >= 100:
  32.       self.res1 += hundreds[(num // 100) - 1]
  33.       if num % 100 != 0:
  34.         return self.convert_to_roman(num % 100)
  35.       else:
  36.         return self.res1
  37.     elif num >= 10:
  38.       self.res1 += tens[(num // 10) - 1]
  39.       if num % 10 != 0:
  40.         return self.convert_to_roman(num % 10)
  41.       else:
  42.         return self.res1
  43.     else:
  44.       self.res1 += ones[num - 1]
  45.       return self.res1
  46.    
  47.   def convert_to_number(self, rom):
  48.     """
  49.    this function converts roman numerals to an integer
  50.    """
  51.    
  52.     # roman numeral symbols and their equivalents
  53.     thousands = {"M":1000, "MM":2000, "MMM":3000, "MMMM":4000, "V̅":5000}
  54.     hundreds = {"C":100, "CC":200, "CCC":300, "CD":400, "D":500, "DC":600, "DCC":700, "DCCC":800, "CM":900}
  55.     tens = {"X":10, "XX":20, "XXX":30, "XL":40, "L":50, "LX":60, "LXX":70, "LXXX":80, "XC":90}
  56.     ones = {"I":1, "II":2, "III":3, "IV":4, "V":5, "VI":6, "VII":7, "VIII":8, "IX":9}
  57.    
  58.     # reverse the dictionaries (using list technique)
  59.     thousands = dict(reversed(list(thousands.items())))
  60.     hundreds = dict(reversed(list(hundreds.items())))
  61.     tens = dict(reversed(list(tens.items())))
  62.     ones = dict(reversed(list(ones.items())))
  63.    
  64.     # conversion (linear-search)
  65.     # for thousands place
  66.     if len(rom) > 0:
  67.       if rom[0] == "M":
  68.         for th in thousands:
  69.           if th in rom:
  70.             self.res2 += thousands[th]
  71.             rom = rom[len(th):]
  72.             break
  73.    
  74.     # for hundreds place
  75.     if len(rom) > 0:
  76.       if rom[0] == "C" or rom[0] == "D":
  77.         for h in hundreds:
  78.           if h in rom and h != "D":
  79.             self.res2 += hundreds[h]
  80.             rom = rom[len(h):]
  81.             break
  82.         if len(rom) > 0:
  83.           if "D" in rom:
  84.             self.res2 += hundreds["D"]
  85.             rom = rom[1:]
  86.    
  87.     # for tens place
  88.     if len(rom) > 0:
  89.       if rom[0] == "X" or rom[0] == "L":
  90.         for t in tens:
  91.           if t in rom and t != "L":
  92.             self.res2 += tens[t]
  93.             rom = rom[len(t):]
  94.             break
  95.         if len(rom) > 0:
  96.           if "L" in rom:
  97.             self.res2 += tens["L"]
  98.             rom = rom[1:]
  99.    
  100.     # for ones place
  101.     if len(rom) > 0:
  102.       if rom[0] == "I" or rom[0] == "V":
  103.         for o in ones:
  104.           if o in rom and o != "V":
  105.             self.res2 += ones[o]
  106.             rom = rom[len(o):]
  107.             break
  108.         if len(rom) > 0:
  109.           if "V" in rom:
  110.             self.res2 += ones["V"]
  111.             rom = rom[1:]
  112.    
  113.     return (self.res2 if len(rom) == 0 else 0)
  114.  
  115. def main():
  116.   while True:
  117.     # menu
  118.     print("MENU\n")
  119.     print("1. convert an integer to a roman numeral")
  120.     print("2. convert a roman numeral to an integer")
  121.     print("3. exit\n")
  122.    
  123.     # menu - input with error-handling
  124.     ch = eval(input("Enter your choice:"))
  125.     if ch < 1 or ch > 3:
  126.       print("INVALID INPUT: Select from 1 to 3 only.\n")
  127.       continue
  128.     elif type(ch) != int:
  129.       print("INVALID INPUT: Whole number only.\n")
  130.       continue
  131.    
  132.     if ch == 1:
  133.       # two (2) cases for both input and output
  134.       inp1 = "Enter Integer - "
  135.       inp2 = "EnterInteger - "
  136.       output1 = "Output in Roman numerals is: {0}\n"
  137.       output2 = "Output in Roman Numberals is {0}\n"
  138.      
  139.       for i in range(2):
  140.         # choice 1 - input with error handling
  141.         n = 0
  142.         while True:
  143.           n = eval(input(inp1 if (i + 1) & 1 else inp2))
  144.           if n <= 0 or n > 5000:
  145.             print("INVALID INPUT: Select from 1 to 5000 only.\n")
  146.             continue
  147.           elif type(n) != int:
  148.             print("INVALID INPUT: Whole number only.\n")
  149.             continue
  150.           else:
  151.             break
  152.            
  153.         # object instantiation
  154.         rn = RomanNumerals()
  155.        
  156.         # output
  157.         ans = rn.convert_to_roman(n)
  158.         print(output1.format(ans) if (i + 1) & 1 else output2.format(ans))
  159.     elif ch == 2:
  160.       # two (2) cases for both input and output
  161.       inp1 = "Enter roman numeral - "
  162.       inp2 = "Enter roman numberals - "
  163.       output1 = "Output in Integer is - {0}\n"
  164.       output2 = "Output in Integer is - {0}\n"
  165.      
  166.       for i in range(2):
  167.         rom = ""
  168.         while True:
  169.           # choice 2 - input with error handling
  170.           rom = str(input(inp1 if (i + 1) & 1 else inp2))
  171.           rom = rom.upper()
  172.          
  173.           # object instantiation
  174.           rn = RomanNumerals()
  175.           ans = rn.convert_to_number(rom)
  176.          
  177.           # output with error-handling
  178.           if ans != 0:
  179.             print(output1.format(ans) if (i + 1) & 1 else output2.format(ans))
  180.             break
  181.           else:
  182.             print("INVALID INPUT: Please try again.\n")
  183.             continue
  184.        
  185.     else:
  186.       print("Program Exiting...")
  187.       break
  188.  
  189. main()
  190.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement