samedi 29 mai 2021

The program doesn't compare two number properly

The comparision operator doesn't work properly

class Solution:
    def romanToInt(self, s: str) -> int:
        dic = {"I":1,"V":5,"X":10,"L":50,"C":100,"D":500,"M":1000}
        result = 0
        s = list(s)
        while True:
            if len(s) == 1:
                x = s.pop(0)
                result+=dic[x]
                break
            elif len(s) == 0:
                break
            else:

The comparision operator doesn't work properly

                if (dic[s[0]] < dic[s[1]]) == True: #gives true for 1000<10
                    result += dic[s[1]] - dic[s[0]]
                    s.pop(0)
                    s.pop(0)

It directly jumps here

                elif (dic[s[0]] >= dic[s[1]] )== True:
                    result += dic[s[1]] + dic[s[0]]
                    s.pop(0)
                    s.pop(0)

        return result


o = Solution()
print(o.romanToInt("MCMXCIV"))

Aucun commentaire:

Enregistrer un commentaire