我有一个简单的任务要转换成roman to int美元.这是我一直在try 的代码.
def romanToInt(s):
"""
:type s: str
:rtype: int
"""
j=0
print(len(s))
for i in range(len(s)):
k=s[i]
l=i+1
if s[i]=="I":
if s[l]=="V":
j+=4
elif s[l]=="X":
j+=9
elif s[i]=="X":
if s[l]=="L":
j+=40
elif s[l]=="C":
j+=90
elif s[i]=="C":
if s[l]=="D":
j+=400
elif s[l]=="M":
j+=900
else:
match k :
case "I":
j+=1
case "V":
j+=5
case "X":
j+=10
case "L":
j+=50
case "C":
j+=100
case "D":
j+=500
case "M":
j+=1000
return j
a=input("Enter number")
b=romanToInt(a)
print(b)
此代码会给出此错误.
Enter numberIII
3
Traceback (most recent call last):
File "C:\Users\admin\Desktop\Dekstop Folder\pycharm\python\Leetcode\Roman to int.py", line 46, in <module>
b=romanToInt(a)
^^^^^^^^^^^^^
File "C:\Users\admin\Desktop\Dekstop Folder\pycharm\python\Leetcode\Roman to int.py", line 13, in romanToInt
if s[l]=="V":
~^^^
IndexError: string index out of range
Process finished with exit code 1
我不知道为什么它显示字符串索引超出范围.
我试着打印了长度,它在范围内,但我不知道为什么它不工作.请帮帮忙.