验证字符串是否为罗马数字

2024-06-14 18:53:01 发布

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

我正在制作一个程序,接收罗马数字并将其转换为十进制。下面的代码在一个函数中,用于验证这个ir是否真的是罗马数字。我的想法是识别像“IXI”或“VIV”这样的数字,因为它看起来像罗马数字,但事实并非如此。我该怎么做

    for i in value:
        if value[i] == 'V' and value[i] == value[i+2] and value[i] != value[i+1]:
            print("It's not a Roman Number")

控制台:

TypeError: list indices must be integers or slices, not str

Tags: and函数代码in程序forifir
1条回答
网友
1楼 · 发布于 2024-06-14 18:53:01

试试这个代码

def roman_to_int(value):
    rom_val = {'I': 1, 'V': 5, 'X': 10, 'L': 50, 'C': 100, 'D': 500, 'M': 1000}
    int_val = 0

    if set(value) - set(rom_val.keys()):
        print("It's not a Roman Number")
    else:
        for i in range(len(value)):
            if i > 0 and rom_val[value[i]] > rom_val[value[i - 1]]:
                int_val += rom_val[value[i]] - 2 * rom_val[value[i - 1]]
            else:
                int_val += rom_val[value[i]]
        return int_val

roman_to_int('V') # 5
roman_to_int('VI') # 6
roman_to_int('IXI') # 10
roman_to_int('TI') # It's not a Roman Number

相关问题 更多 >