0

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?

jscs
  • 63,694
  • 13
  • 151
  • 195
muzikmoe
  • 121
  • 1
  • 2
  • 10

2 Answers2

0

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'

John La Rooy
  • 295,403
  • 53
  • 369
  • 502
0

numeral is equal to CM and len(cm) == 2. s[1: 1 + 2] == s[1:3] == 'CM'

Since the numeral is actually two characters, you read two characters of the input to match against.

Russell Cohen
  • 717
  • 4
  • 7
  • If I write the (CM, 900) behind (C, 100), then the result will be C ? More to question, Is the while procedure obey a certain order of the elements it checks? – muzikmoe Nov 30 '15 at 06:11
  • Are you aware that CM is something different than MC in Roman numbers? Now, concerning the while procedure, the order it checks the map is in the order it is given, due to the surrounding `for` loop. – Ulrich Eckhardt Nov 30 '15 at 06:15
  • @UlrichEckhardt I know the difference between them. And do you mean the order of elements within the map given to while procedure determines the while check order? – muzikmoe Nov 30 '15 at 06:21
  • I think you should step through this program and inspect what variables contain at certain stages, that would clear up your questions immediately. – Ulrich Eckhardt Nov 30 '15 at 06:25