解释罗马数字并返回数字值

2024-04-25 06:00:42 发布

您现在位置:Python中文网/ 问答频道 /正文

print ('please enter a roman numeral')
romannum = input()
lenrm = len(romannum)
total = 0
for i in range (lenrm):
    numone = 0
    numtwo = 0

    if (romannum[i]).lower() == 'i':
        numone = numone + 1

    if (romannum[i]).lower() == 'v':
        numone = numone + 5

    if (romannum[i]).lower() == 'x':
        numone = numone + 10

    if (romannum[i + 1]).lower() == 'i':
        numtwo = numtwo + 1

    if (romannum[i + 1]).lower() == 'v':
        numtwo = numtwo + 5

    if (romannum[i + 1]).lower() == 'x':
        numtwo = numtwo + 10


    if numone < numtwo:
        total = total + (numtwo - numone)
    else:
        total = total + numone
        i += 1
print (total)

输入xiv,我得到一条错误消息

Traceback (most recent call last):
  File "C:\Users\poona\Python\roman_numeral_reader.py", line 18, in <module>
    if (romannum[i + 1]).lower() == 'i':
IndexError: string index out of range

Tags: ininputifrangelowertotalprintenter
3条回答

所以你有一个长度为5的输入,比如说IIIII,现在你取范围(5),这意味着它将迭代的最高值是4(从0到4,包括这两个),现在索引4是你的5索引长数值中的最后一个索引,因为我们从0开始计算索引,所以当你加上1,你得到的索引5超出了范围。你知道吗

对你来说

romannum = "xiv"
lenrm = 3
total = 0
for i in [0,1,2]: # for i in range(3):
    ...
    if (romannum[3]).lower() == 'i': # if (romannum[i + 1]).lower() == 'i':
def rom2dec(char):
    for s in (('I', 1), ('V', 5), ('X', 10), ('L', 50),
              ('C', 100), ('D', 500), ('M', 1000)):
        if char == s[0]: return s[1]

total=0
prev=0
romannum = input('Roman Numeral: ').upper()

for s in reversed(romannum):
    i = rom2dec(s)

    if i < prev:
        total -= i
    else:
        total += i

    prev = i

print(total)

你的问题是错误string index out of range 表示您正试图访问字符索引 不在字符串长度的范围内。 字符串基于0,因此第一个字符位于索引0处。你知道吗

使用romannum[i + 1]时,您需要确保 i + 1不大于存储的字符串的长度 在名为romannum的变量中减去1,因为它是基于0的。你知道吗

罗马数字往往与求和相反 i、 e.I之前的V被解释为4,因为I小于 V并在V之前。你知道吗

因此,如果字符串被反转,则将每个字符改为 十进制等价,然后与上次存储的十进制进行比较 值,以确定是否要添加或减去当前十进制数。你知道吗

这看起来很简单,您试图访问xivv旁边的字符,当然,这是越界的。你知道吗

我建议在确定下一个字符之前检查边界:

for i in range (lenrm):
    numone = 0
    numtwo = 0

    if (romannum[i]).lower() == 'i':
        numone = numone + 1

    if (romannum[i]).lower() == 'v':
        numone = numone + 5

    if (romannum[i]).lower() == 'x':
        numone = numone + 10

    if i + 1 < lenrm:  # <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
        if (romannum[i + 1]).lower() == 'i':
            numtwo = numtwo + 1

        if (romannum[i + 1]).lower() == 'v':
            numtwo = numtwo + 5

        if (romannum[i + 1]).lower() == 'x':
            numtwo = numtwo + 10

相关问题 更多 >