Write a Python program to implement a simple, interactive calculator. This program permits the binary operators: '+' (addition), - (subtraction), * (multiplication) and / (division); the unary operator ~ (negation); and = (to print an answer). The program uses the postfix notation for arithmetic expressions. Arithmetic is performed on floating- point numbers. A stack data structure is used to keep input numbers and partial results. For the stack structure, and additional operator c is permitted to empty the stack. In the input file

In your Python program, include the following functions:

  • def main ( ): Creates an empty stack, gets the text input from the stdin (keyboard) and calls the function proc_input ( ) to process the input. At the end of your program file, the only routine that you need to call is this routine without any arguments.
  • def proc_input ( text, stack ): Splits the text into individual tokens (strings without any white spaces). If the token is corresponding to a number, converts it to a floating-point number and push it onto the stack. If the token is an arithmetic operator, performs the operator on the top element(s) of the stack. For a binary operator, it calls the function bin_op ( ) to perform the operation. If the token is '=' sign, displays the top element of the stack on stdout. If the token is c, empty the stack for a fresh start. For an unknown operand, it prints an error message on stderr. Numbers printed on stdout should have three decimal digits after the decimal point and they should be right aligned.
  • def bin_op ( op1, op2, operator): Performs the binary operation applying the operator on the operands op1 and op2 and returns the result to the calling function. For a division operation, if op2 == 0, it prints an error message on stderr and returns None.

You can implement a stack structure by using a list. For the stack, include the following functions:

  • def Push ( x, stack ): Pushes the element x onto the stack.
  • def Pop ( stack ): Pops and returns the value of top element of the stack. If the stack is empty, it prints an error message on stderr and returns None.
  • def Top (stack ): Returns the value of the top element of the stack. If the stack is empty, it prints an error message on stderr and returns None.
  • def clear ( stack ): Empties the stack.
Academic Honesty!
It is not our intention to break the school's academic policy. Posted solutions are meant to be used as a reference and should not be submitted as is. We are not held liable for any misuse of the solutions. Please see the frequently asked questions page for further questions and inquiries.
Kindly complete the form. Please provide a valid email address and we will get back to you within 24 hours. Payment is through PayPal, Buy me a Coffee or Cryptocurrency. We are a nonprofit organization however we need funds to keep this organization operating and to be able to complete our research and development projects.