我尝试了以下从罗马到整数的python3代码
代码一目了然运行良好。但是,当我输入X
、V
或与X
和V
值相关时,出现了某些问题
例如:当我尝试V
时,代码不起作用,但IV
显示正确的值
我的代码:
class Solution(object):
def romanToInt(self, s):
"""
:type s: str
:rtype: int
"""
roman = {'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}
i = 0
num = 0
while i < len(s):
if i+1<len(s) and s[i:i+2] in roman:
num+=roman[s[i:i+2]]
i+=2
else:
#print(i)
num+=roman[s[i]]
i+=1
return num
ob1 = Solution()
message = str(input("Please enter your roman number: "))
if message <= ("MMMCMXCIX"):
print (ob1.romanToInt(message))
else:
print ("Try again")
我设置了一个条件,如果输入的罗马数字等于或小于MMMCMXCIX
,它将打印罗马数字;否则它将打印Try again
问题是当我输入X
、V
或与X
和V
相关的值时,输出显示Try again
请帮助我理解我哪里出了错
正如注释中提到的,问题是因为比较了字符串而不是首先转换为int,然后进行比较
您可以尝试的其他方法是:
在我看来,两者都更像Python
最后,它只是一个数字的加法,你只需要弄清楚它们是否需要被解释为正数或负数:
输出:
这是因为您要比较字符串,而不是首先将罗马字符转换为int而不是check
相关问题 更多 >
编程相关推荐