I am learning Python 2.7 by Dive to Python. Here are the codes of "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')
But I am puzzled by the procedure of this part:
for numeral, integer in romanNumeralMap:
while s[index:index+len(numeral)] == numeral:
result += integer
index += len(numeral)
When executed in the second time, the s[index:index+len(numeral)]
returns CM
, but I think it should return C
, because the index = 1
after the first execution, then index+len(numeral) = 2
, and s[1: 2] = 'C'
. What's wrong with my understanding?
On the second iteration of the for
loop, index
is indeed 1
numeral
is CM
and integer
is 900
len(numeral)
== 2
, and
s[1:1+2]
== S[1:3]
== 'CM'