Donate. I desperately need donations to survive due to my health

Get paid by answering surveys Click here

Click here to donate

Remote/Work from Home jobs

Getting a Prefix or Postfix Expression as input from user in Python

So, I was trying out this program, I was able to write a function that calculates the postfix expression which worked fine. But when I tried to accept the input from the user, it throws me error. Any help would be great. I just want to know how to pass an a postfix expression during the runtime as input and get the output out of it. I have attached my code.

from pythonds.basic.stack import Stack

postfixexpr = input()

def postfixEval(postfixexpr):
operandStack = Stack()
tokenList = postfixexpr.split()

for token in tokenList:
    if token in "123456789":
        operandStack.push(int(token))
    else:
        operand2 = operandStack.pop()
        operand1 = operandStack.pop()
        result = doMath(token,operand1, operand2)
        operandStack.push(result)
return operandStack.pop()

def doMath(op, op1, op2):
if op == "*":
    return op1 * op2
elif op == "/":
    return op1 / op2
elif op == "+":
    return op1 + op2
elif op == "-":
    return op1 - op2


print (postfixEval('postfixexpr'))
#print (postfixEval('7 8 + 3 6 + *'))

Please help me design the code such a way I can let users to pass their input.

Am also adding the error which I got.

IndexError                                Traceback (most recent call last)
<ipython-input-11-baaa44415c97> in <module>
 28 
 29 
---> 30 print (postfixEval('postfixexpr'))
 31 #print (postfixEval('7 8 + 3 6 + *'))

<ipython-input-11-baaa44415c97> in postfixEval(postfixexpr)
 11             operandStack.push(int(token))
 12         else:
---> 13             operand2 = operandStack.pop()
 14             operand1 = operandStack.pop()
 15             result = doMath(token,operand1, operand2)

~\AppData\Roaming\Python\Python37\site-packages\pythonds\basic\stack.py in      
pop(self)
 16 
 17     def pop(self):
 ---> 18         return self.items.pop()
 19 
 20     def peek(self):

IndexError: pop from empty list

Thanks

Comments