Home > Blockchain >  How can I make my code more efficient for Roman to Integer conversion?
How can I make my code more efficient for Roman to Integer conversion?

Time:08-20

I'm new to programming. In Python, I wrote a program to convert Roman numerals to integers. The constraints are:

1 <= s.length <= 15
s contains only the characters ('I', 'V', 'X', 'L', 'C', 'D', 'M').
It is guaranteed that s is a valid roman numeral in the range [1, 3999].

How can I make this run faster?

Here is my code:

class Solution:
    def romanToInt(self, s: str) -> int:
        intList = []
        for i in s:
            if i == 'I':
                intList.append(1)
            elif i == 'V':
                intList.append(5)
            elif i == 'X':
                intList.append(10)
            elif i == 'L':
                intList.append(50)
            elif i == 'C':
                intList.append(100)
            elif i == 'D':
                intList.append(500)
            elif i == 'M':
                intList.append(1000)
        
        sum = 0
        skip = True
        for number in range(len(intList)):
            if (number < len(intList) - 1) and (intList[number] < intList[number   1]):
                sum  = intList[number   1] - intList[number]
                skip = False
            elif (not skip):
                skip = True
                continue
            else:
                sum  = intList[number]
                
        return sum

CodePudding user response:

Will approach this by using dictionary like this; Just compare and do the right ops. Except the last one, if one letter is less than its latter one, this letter is subtracted.


 def romanToInt(self, s: str) -> int:
        ans = 0
        prev = 0
        dc = {'I':1,'V':5,'X':10,'L':50,'C':100,'D':500,'M':1000}
        
        for c in s[::-1]:
            v = dc[c]           # based on @Stuart suggestion
            if prev > v:
                ans -= v
            else:
                ans  = v
                prev = v
        return ans

# check it out.... using these "XII" "XXVII" "MMXX"

CodePudding user response:

try to call this method by passing the roman string

def romanToInt(self, s: str) -> int:
    ref_obj = {
'I': 1,
'V': 5,
'X': 10,
'L': 50,
'C': 100,
'D': 500,
'M': 1000,
'IV': 4,
'IX': 9,
'XL': 40,
'XC': 90,
'CD': 400,
'CM': 900
}
    total = 0
    i = 0
    while i < len(s):
        if i   1 < len(s) and ref_obj[s[i]] < ref_obj[s[i   1]]:
            total = total   ref_obj[s[i]   s[i   1]]
            i = i   2
        else:
            total = total   ref_obj[s[i]]
            i = i   1
    return total    
  • Related