首页 > 解决方案 > 该程序没有正确比较两个数字

问题描述

比较运算符无法正常工作

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:

比较运算符无法正常工作

                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)

直接跳到这里

                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"))

标签: pythonpython-3.xif-statementoutputcomparison

解决方案


推荐阅读