Home > OS >  Is there any way I can shorten this roman to int program? (python)
Is there any way I can shorten this roman to int program? (python)

Time:11-28

I'm writing a roman numeral to integers program and was testing some preexisting code with a few modifications I made.

list1={'I':1,'IV':4,'V':5,'IX':9,'X':10,'XL':40,'L':50,'XC':90,'C':100,'CD':400,'D':500,'CM':900,'M':1000}
def romanint(str):
    result=0
    count=0
    while (count < len(str)):
      value1 = list1[str[count]]
      if (count   1 < len(str)):
        value2 = list1[str[count   1]]
        if (value1 >= value2):
          result = result   value1
          count = count   1
        else:
          result = result   value2 - value1
          count = count   2
      else:
        result = result   value1
        count = count   1
    return result
x=input("Please enter a Roman numeral: ")
print(romanint(x))

It works fine but I feel like there's a way to shorten it. I've tried to delete lines I've felt were unnecessary but errors always pop up. Is there a way to modify it or is it fine the way it is?

CodePudding user response:

Check out the roman library, pip install roman the info is here on their gitgub. Assuming that you are simply trying to optimize a roman numeral converter.

CodePudding user response:

As your motive is to shorten the code..

I have used replace() function.

Code:-

def romanToInt(s: str):
    translations = {"I": 1,"V": 5,"X": 10,"L": 50,"C": 100,"D": 500,"M": 1000}
    number=0
    s=s.replace("IV", "IIII").replace("IX", "VIIII")
    s=s.replace("XL", "XXXX").replace("XC", "LXXXX")
    s=s.replace("CD", "CCCC").replace("CM", "DCCCC")
    for char in s:
        number =translations[char]
    return number

# Testcase 1 s="III"
print(romanToInt("III"))
# Testcase 2 s="MCMXCIV"
print(romanToInt("MCMXCIV"))
# Testcase 3 s="LVIII"
print(romanToInt("LVIII"))

Output:-

3
1994
58

Hope you like it..!

  • Related