Function which takes a string and uses a stack to calculate the value of theequation passed in. This equation is assumed to be in postfix/reverse Polishnotation.
RETURNS: The value that the equation evaluates to using postfix notation
python please :)
Here is the python code to given question.
Sample outputs are added at the end.
Code:
#create stack class
class stack:
#initialize stack
def __init__(self):
self.stackList=[]
self.top=-1
#pushes value into stack
def push(self,value):
self.stackList.append(value) #appends value into stack
self.top+=1 #increments top by 1
#pops the element at top of stack
def pop(self):
if self.top!=-1: #checks if stack is not empty
self.top-=1 #decrements the value of top by 1
return self.stackList.pop() #returns the top element of stack
#function to evaluate postfix expression
def evaluatePostfix(expression):
expressionList=expression.split(' ') #converts string words to list
stackObject=stack() #creates a new stack object
for i in expressionList:
if i.isdigit(): #checks if i is a number
stackObject.push(int(i)) #pushes the number into top of stack
else:
value1=stackObject.pop() #pops element at top of stack
value2=stackObject.pop() #pops element at top of stack
if i=='+':
stackObject.push(int(value2+value1)) #pushes value2+value1 into the stack
elif i=='-':
stackObject.push(int(value2-value1)) #pushes value2-value1 into the stack
elif i=='*':
stackObject.push(int(value2*value1)) #pushes value2*value1 into the stack
elif i=='/':
stackObject.push(int(value2/value1)) #pushes value2/value1 into the stack
elif i=='^':
stackObject.push(int(value2**value1)) #pushes value2**value1 into the stack
return stackObject.pop() #returns top element of stack
def main():
inputExpression=input("Enter postfix expression: ") #takes input expression from user
print(evaluatePostfix(inputExpression)) #calls evaluatePostfix method and prints the value returned
if __name__=="__main__":
main() #calls main
Sample output-1:
Sample output-2:
Get Answers For Free
Most questions answered within 1 hours.