Question:
I’m trying to understand a function in Python meant to convert Roman numerals to integers. In the following code:roman = {‘I’:1,’V’:5,’X’:10,’L’:50,’C’:100,’D’:500,’M’:1000,’IV’:4,’IX’:9,’XL’:40,’XC’:90,’CD’:400,’CM’:900} If you have better answer, please add a comment about this, thank you!
s = “III”
i = 0
num = 0
while i < len(s):
if i+1
Appreciate any and all help!
Answer:
The first time through the loop, i = 0
and s[i:i+2] = 'II'
. 'II' in roman
is not true, so we go to the else:
block. s[i] = 'I'
, and roman['I'] = 1
, so we add 1 to num
, which now equals 1
. We also add 1
to i
.
The second time through the loop, i = 1
and s[i:i+2] = 'II'
. Again, that’s not a key in the dictionary, so we go to the else:
block and add roman['I']
to num
. So now num = 2
. We also add 1
to i
.
The third time through the loop, i = 2
and i+1 < len(s)
is false. So we go to the else:
block. s[i] = 'I'
again, so we we add 1
to num
again. Now num = 3
. We also add 1
to i
.
Now i = 3
and the condition while i < len(s):
is no longer true, so the loop ends.
We never get a key error because we always check whether II
is a key in the dictionary before trying to access roman['II']
.