fork download
  1. def solve_postfix(postfix_exp):
  2. stack = []
  3.  
  4. # Function to perform arithmetic operations
  5. def perform_operation(op, num1, num2):
  6. if op == '+':
  7. return num1 + num2
  8. elif op == '-':
  9. return num1 - num2
  10. elif op == '*':
  11. return num1 * num2
  12. elif op == '/':
  13. return num1 / num2
  14.  
  15. for char in postfix_exp:
  16. if char.isdigit():
  17. stack.append(int(char))
  18. elif char in "+-*/":
  19. # Pop the top two numbers from the stack
  20. num2 = stack.pop()
  21. num1 = stack.pop()
  22. # Perform the operation and push the result back onto the stack
  23. result = perform_operation(char, num1, num2)
  24. stack.append(result)
  25.  
  26. # The final result should be on the top of the stack
  27. return stack.pop()
  28.  
  29. # Example usage:
  30. postfix_exp = "481*+3-"
  31. result = solve_postfix(postfix_exp)
  32. print(result) # Output should be 15
Success #stdin #stdout 0.03s 9788KB
stdin
Standard input is empty
stdout
9