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

def blanks(exprlist):
    for n, token in enumerate(exprlist):
        if exprlist[n] == '(' and exprlist[n+1] == ')':
            print(f"Invalid expression, expecting operand between {' '.join(exprlist[:n+1])} and {' '.join(exprlist[n+1:])}")
            return False
        elif exprlist[n] == ')' and exprlist[n+1] == '(':
            print(f"Invalid expression, expecting operator {' '.join(exprlist[:n+1])} and {' '.join(exprlist[n+1:])} ")
            return False
    elif exprlist[n] == ')' and exprlist[n+1] in ')//+-**':
            return True
    return True

def main():
    expr = input('Enter expression: ')
        if expr == '':
            print('Application ended')
            break
    if blanks(exprlist):
        eval(expr)
    else:
        continue

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

Advertisement

Answer

Here:

for n, token in enumerate(exprlist):
    if exprlist[n] == '(' and exprlist[n+1] == ')':

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:

for token, next_token in zip(exprlist, exprlist[1:]):
    if token == '(' and next_token == ')':
        # etc
Advertisement