从 Dive 中的罗马数字转换为 Python 似乎会输出一个额外的字符
Conversion from Roman numerals in Dive into Python seems to output an extra character
我正在学习 Python 2.7,方法是 Dive to Python。这是"Converting between Roman Numerals and Arabic numerals"的代码:
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)]
return秒CM
,不过我觉得应该是return C
,因为index = 1
先执行后,然后index+len(numeral) = 2
,然后s[1: 2] = 'C'
。我的理解有什么问题吗?
在 for
循环的第二次迭代中,index
确实是 1
numeral
是 CM
而 integer
是 900
len(numeral)
== 2
,以及
s[1:1+2]
== S[1:3]
== 'CM'
numeral
等于 CM
和 len(cm) == 2
。 s[1: 1 + 2] == s[1:3] == 'CM'
由于数字实际上是两个字符,因此您读取输入的两个字符以进行匹配。
我正在学习 Python 2.7,方法是 Dive to Python。这是"Converting between Roman Numerals and Arabic numerals"的代码:
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)]
return秒CM
,不过我觉得应该是return C
,因为index = 1
先执行后,然后index+len(numeral) = 2
,然后s[1: 2] = 'C'
。我的理解有什么问题吗?
在 for
循环的第二次迭代中,index
确实是 1
numeral
是 CM
而 integer
是 900
len(numeral)
== 2
,以及
s[1:1+2]
== S[1:3]
== 'CM'
numeral
等于 CM
和 len(cm) == 2
。 s[1: 1 + 2] == s[1:3] == 'CM'
由于数字实际上是两个字符,因此您读取输入的两个字符以进行匹配。