我接到了一项任务,要把罗马数字转换成整数,并能想出以下解决方案:

def roman_numeral_to_int(string):
    symbols = {
        'I': 1,
        'V': 5,
        'X': 10,
        'L': 50,
        'C': 100,
        'D': 500,
        'M': 1000
    }
    repetitions = {}
    result = 0
    skip = 0
    for i, c in enumerate(string):
        if i == skip and i != 0:
            continue
        if c not in symbols:
            return None
        if c in repetitions.items():
            repetitions[c] += 1
        else:
            repetitions = {c: 1}
        for r, v in repetitions.items():
            if (r in ['L', 'D', 'V'] and v > 1) or (r in ['I', 'X', 'C'] and v > 3):
                return None
        if c == 'I':
            # last character in the string
            if i == len(string) - 1:
                result += 1
            elif string[i+1] == 'V':
                result += 4
                skip = i + 1
            elif string[i+1] == 'X':
                result += 9
                skip = i + 1
        elif c == 'X':
            # last character in the string
            if i == len(string) - 1:
                result += 10
            elif string[i+1] == 'L':
                result += 40
                skip = i + 1
            elif string[i+1] == 'C':
                result += 90
                skip = i + 1
        elif c == 'C':
            # last character in the string
            if i == len(string) - 1:
                result += 100
            elif string[i+1] == 'D':
                result += 400
                skip = i + 1
            elif string[i+1] == 'M':
                result += 900
                skip = i + 1
        else:
            skip = 0
            result += symbols[c]
    return result

但是,这个解决方案得到了错误的答案,字符串MLXVI应该输出1066,而这个代码生成1056。
有人能指出这个解决方案有什么问题吗?

最佳答案

通过在此块中添加else语句,可以修复该特定情况:

elif c == 'X':
    # last character in the string
    if i == len(string) - 1:
        result += 10
    elif string[i+1] == 'L':
        result += 40
        skip = i + 1
    elif string[i+1] == 'C':
        result += 90
        skip = i + 1
    else:
        result += 10

但是我发现这可能发生在其他地方,比如multipleIs.SoIII应该是3,但是程序返回1。

关于python - 将罗马数字转换为整数,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/48801826/

10-11 04:10