Skip to content
Advertisement

Iterate through a loop and stopping when the last index == ‘)]

I am currently trying to do something like a calculator where invalid inputs produce an error. However, I am running into an error where they say the index is out of the list when i input ( 2 + 7 ). So instead, I was thinking that if I can the loop if the last index of the list is == ‘)’. For the purpose of this exercise, each item in the list is split with a space. split( )

I am unable to import any libraries

JavaScript

The expected output is that the program is supposed to eval( 2 + 7 ) instead of running into the error.

Advertisement

Answer

Here:

JavaScript

when you reach the last item, n is the index of the last item, so there isn’t anything at n+1 indeed.

The pythonic solution here is to use zip() to generate a sequence of (item, next_item) pairs:

JavaScript
Advertisement