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
x
22
22
1
def blanks(exprlist):
2
for n, token in enumerate(exprlist):
3
if exprlist[n] == '(' and exprlist[n+1] == ')':
4
print(f"Invalid expression, expecting operand between {' '.join(exprlist[:n+1])} and {' '.join(exprlist[n+1:])}")
5
return False
6
elif exprlist[n] == ')' and exprlist[n+1] == '(':
7
print(f"Invalid expression, expecting operator {' '.join(exprlist[:n+1])} and {' '.join(exprlist[n+1:])} ")
8
return False
9
elif exprlist[n] == ')' and exprlist[n+1] in ')//+-**':
10
return True
11
return True
12
13
def main():
14
expr = input('Enter expression: ')
15
if expr == '':
16
print('Application ended')
17
break
18
if blanks(exprlist):
19
eval(expr)
20
else:
21
continue
22
The expected output is that the program is supposed to eval( 2 + 7 )
instead of running into the error.
Advertisement
Answer
Here:
JavaScript
1
3
1
for n, token in enumerate(exprlist):
2
if exprlist[n] == '(' and exprlist[n+1] == ')':
3
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
1
4
1
for token, next_token in zip(exprlist, exprlist[1:]):
2
if token == '(' and next_token == ')':
3
# etc
4