• python
  • javascript
  • reactjs
  • sql
  • c#
  • java
Facebook Twitter Instagram
Devs Fixed
  • python
  • javascript
  • reactjs
  • sql
  • c#
  • java
Devs Fixed
Home » Resolved: In Python3 does num+=roman[s[i:i+2]] not throw key error in loop?

Resolved: In Python3 does num+=roman[s[i:i+2]] not throw key error in loop?

0
By Isaac Tonny on 17/06/2022 Issue
Share
Facebook Twitter LinkedIn

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}
s = “III”
i = 0
num = 0
while i < len(s): if i+1 The if statement somehow gives an answer of 2, but when I think it through it looks like it should only loop through the if statement once and give 1. But when I think it through further and isolate this section I get a key error ‘II’ which makes sense. So how is the loop not throwing this error and giving a value of 2?
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'].

If you have better answer, please add a comment about this, thank you!

python
Share. Facebook Twitter LinkedIn

Related Posts

Resolved: Getting ‘502 Bad Gateway’ while deploying Springboot app in EKS

24/03/2023

Resolved: Why is NGINX’s $request_uri empty?

24/03/2023

Resolved: How to convert Java bytecode to Webassembly using CheerpJ compiler

24/03/2023

Leave A Reply

© 2023 DEVSFIX.COM

Type above and press Enter to search. Press Esc to cancel.