You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

罗马数字转换器中KeyError: 0问题的解决方法

罗马数字转整数函数KeyError问题排查与解决

问题描述

实现了罗马数字转整数的romanToInt函数,自认为逻辑正确,但运行时触发KeyError: 0,报错指向roman_table[numeral]的调用。

原始代码

def romanToInt(s: str) -> int:
    roman_table = {"I": 1, "V": 5, "X": 10, "L": 50, "C": 100, "D": 500, "M": 1000}
    result = 0

    for numeral in range(len(s)):
        if (
            numeral + 1 < len(s)
            and roman_table[s[numeral]] < roman_table[s[numeral + 1]]
        ):
            result -= roman_table[numeral]
        else:
            result += roman_table[numeral]

    return result


romanToInt("MCMXCIV")

终端报错信息

$ python to_roman_numeral_converter.py
Traceback (most recent call last):
  File "C:Users\XYZ\dev\repos\roman_numeral\to_roman_numeral_converter.py", line 14, in <module>
    romanToInt("MCMXCIV")
  File "C:\Users\XYZ\dev\repos\roman_numeral\to_roman_numeral_converter.py", line 6, in romanToInt
    if numeral + 1 < len(s) and roman_table[numeral] < roman_table[numeral + 1]:
KeyError: 0

问题原因

  • 循环变量numeral是range(len(s))生成的索引数字(如0、1、2...),但roman_table的键是罗马字符("I"、"V"等),不存在数字类型的键,直接用roman_table[numeral]会触发KeyError。
  • 你在条件判断里已经正确使用s[numeral]获取对应位置的罗马字符,但在对result做加减操作时,错误地用numeral(索引数字)代替了s[numeral](罗马字符)。

解决办法

将加减逻辑中的roman_table[numeral]替换为roman_table[s[numeral]],确保从字典中取的是罗马字符对应的值。

修正后的代码

def romanToInt(s: str) -> int:
    roman_table = {"I": 1, "V": 5, "X": 10, "L": 50, "C": 100, "D": 500, "M": 1000}
    result = 0

    for numeral in range(len(s)):
        current_val = roman_table[s[numeral]]
        # 检查下一个字符是否存在且当前值小于下一个值
        if numeral + 1 < len(s) and current_val < roman_table[s[numeral + 1]]:
            result -= current_val
        else:
            result += current_val

    return result


print(romanToInt("MCMXCIV"))  # 输出: 1994

也可以用enumerate遍历字符和索引,代码更直观:

def romanToInt(s: str) -> int:
    roman_table = {"I": 1, "V": 5, "X": 10, "L": 50, "C": 100, "D": 500, "M": 1000}
    result = 0
    n = len(s)
    for idx, char in enumerate(s):
        current_val = roman_table[char]
        if idx + 1 < n and current_val < roman_table[s[idx + 1]]:
            result -= current_val
        else:
            result += current_val
    return result

内容的提问来源于stack exchange,提问作者JnooriRS

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.19 22:35:15