-1

can you please tell me why my if statement isn't working properly? when roman x is before v it shoud minus 2 from the result.

class Solutions:
    def roman_numeral(romanNum):
        value={"I":1,"V":5,"X":10,"L":50,"C":100,"D":500,"M":1000}
        result=0
        for i in value:
            for j in range(len(romanNum)):
                if i==romanNum[j]:
                    result+=value[i]
                    if (romanNum[j]=="I" and romanNum[j+1]=="V") or (romanNum[j]=="I" and romanNum[j]=="X"):
                        print("form I"+i+romanNum[j+1])
                        result=result-2
                    if (romanNum[j]=="X" and romanNum[j+1]=="L") or (romanNum[j]=="X" and romanNum[j]=="C"):
                        result=result-20
                        print("form X"+i+romanNum[j+1])
                    if (romanNum[j]=="C" and romanNum[j+1]=="D") or (romanNum[j]=="C" and romanNum[j]=="M"):
                        result=result-200
                        print("form C"+i+romanNum[j+1])
                
        return result

print(Solutions.roman_numeral("MCMXCIV"))
Azizur Rahaman
  • 181
  • 2
  • 5

1 Answers1

0

Yep!, I have solve it.

class Solution:
def romanToInt(self, s: str) -> int:
    roman_value={"I":1,"V":5,"X":10,"L":50,"C":100,"D":500,"M":1000}
    result=0
    for i in roman_value:
        for j in range(len(s)):
            if i==s[j]:
                result+=roman_value[i]

                try:
                    if s[j]=="I" and s[j+1]=="V" or s[j]=="I" and s[j+1]=="X":
                        result=result-2
                    if (s[j]=="X" and s[j+1]=="L") or (s[j]=="X" and s[j+1]=="C"):
                        result=result-20
                    if (s[j]=="C" and s[j+1]=="D") or (s[j]=="C" and s[j+1]=="M"):
                        result=result-200
                except:
                    pass
                    
            
    return result
Azizur Rahaman
  • 181
  • 2
  • 5
  • Your answer could be improved by adding more information on what the code does and how solved the problem. – Tyler2P Jul 09 '22 at 18:06