从Dive中的罗马数字转换为Python似乎输出了额外的字符

时间:2015-11-30 05:17:45

标签: python arrays roman-numerals

我正在通过 Dive to Python 学习Python 2.7。以下是“罗马数字与阿拉伯数字之间的转换”代码:

romanNumeralMap = (('M',1000),
        ('CM',900),
        ('D',500),
        ('CD',400),
        ('C',100),
        ('XC',90),
        ('L',50),
        ('XL',40),
        ('X',10),
        ('IX',9),
        ('V',5),
        ('IV',4),
        ('I',1))
def toRoman(n):
    result = ""
    for numeral, integer in romanNumeralMap:
        while n >= integer:
            result += numeral
            n -= integer
    return result

def fromRoman(s):
    result = 0
    index = 0
    for numeral, integer in romanNumeralMap:
        while s[index:index+len(numeral)] == numeral:
            result += integer
            index += len(numeral)
    return result

print toRoman(1356)
print fromRoman('MCMLXXII')

但我对这一部分的程序感到困惑:

for numeral, integer in romanNumeralMap:
        while s[index:index+len(numeral)] == numeral:
            result += integer
            index += len(numeral)

时间执行时,s[index:index+len(numeral)]会返回CM,但我认为它应该返回C,因为index = 1之后第一次执行,然后是index+len(numeral) = 2s[1: 2] = 'C'。我的理解有什么问题?

2 个答案:

答案 0 :(得分:0)

for循环的第二次迭代中,index确实是1
numeralCMinteger900

len(numeral) == 2

s[1:1+2] == S[1:3] == 'CM'

答案 1 :(得分:0)

numeral等于CMlen(cm) == 2s[1: 1 + 2] == s[1:3] == 'CM'

由于数字实际上是两个字符,因此您可以读取输入的两个字符以匹配。