1

I'm trying to write some code that converts roman numerals into integers, but I'm running into an issue where when I input 'MCMXCIV', I'm getting 3099 instead of 1994. When I try with smaller numbers like III (3) and LVIII (58), it's converting them correctly. I know there's a more efficient way to write this whole thing, but any assistance with debugging my current code would be much appreciated.

Rules: I can be placed before V (5) and X (10) to make 4 and 9. X can be placed before L (50) and C (100) to make 40 and 90. C can be placed before D (500) and M (1000) to make 400 and 900.

class Solution:
    def romanToInt(self, s: str) -> int:
        romanDict = {
            'I':1,
            'V':5,
            'X':10,
            'L':50,
            'C':100,
            'D':500,
            'M':1000
        }
        
        l = len(s)
        sum = 0
        i = 0
        
        for i in range(l):
            letter = s[i]
            if i+1 < l:
                nextLetter = s[i+1]
                diff = romanDict[nextLetter] - romanDict[letter]
                match letter:
                    case 'I':
                        if nextLetter in ['V', 'X']:
                            sum += romanDict[nextLetter] - romanDict[letter]
                            print (diff)
                            i + 1
                        else: sum += romanDict[letter]
                    case 'X':
                        if nextLetter in ['L', 'C']:
                            sum += romanDict[nextLetter] - romanDict[letter]
                            print (diff)
                            i + 1
                        else: sum += romanDict[letter]
                    case 'C':
                        if nextLetter in ['D', 'M']:
                            sum += romanDict[nextLetter] - romanDict[letter]
                            print (diff)
                            i + 1
                        else: sum += romanDict[letter]
                    case _:
                        sum += romanDict[letter] 
                        print (romanDict[letter])
                        
            else: sum += romanDict[letter]
                       
        return sum
        
coak
  • 11
  • 1
  • Does this answer your question? [Basic program to convert integer to Roman numerals?](https://stackoverflow.com/questions/28777219/basic-program-to-convert-integer-to-roman-numerals) – mr_mooo_cow Sep 09 '22 at 16:52
  • These `i+1` look fishy. You know those lines don't do anything, right? – Sören Sep 09 '22 at 16:52
  • "When I try with smaller numbers like III (3) and LVIII (58), it's converting them correctly" - Have you tried IV (4)? – Sören Sep 09 '22 at 16:53
  • See https://stackoverflow.com/questions/15902835/changing-iteration-variable-inside-for-loop-in-python/15903677#15903677 regarding trying to change the iteration variable when using `for i in range()` – Barmar Sep 09 '22 at 16:58

0 Answers0