Write a Python function ArithmeticCalculator that performs the evaluation of an
ID: 3592781 • Letter: W
Question
Write a Python function ArithmeticCalculator that performs the evaluation of an arithmetic expression and outputs the result on screen.
Requirements:
Your implementation must use ArrayStack class and follow general guidelines of the algorithm. Your function must be able to evaluate operations +, (both binary and unary forms), *, and / (using integer division).
Your function must be able to evaluate correctly an expression with single-level parentheses.
To test your code you can use several hard-coded arithmetic expressions
Assumptions:
One operation per set of parentheses, for simplicity.
Only addition and subtraction operations could be in parentheses; multiplication and division, having highest priority (in the absence of exponent operation) do not require parentheses, nor will be placed in such.
Dealing with more complex expressions (including the case of nested parentheses) for this assignment.
Dealing with interactive user input (i.e., "prompt the user to provide an arithmetic expression; make sure that it is parsed correctly whether or not the user types the expression with extra whitespace; use a loop to allow for multiple expressions to be evaluated") for this assignment.
Explanation / Answer
def add(x, y): return x + y # This function subtracts two numbers def subtract(x, y): return x - y # This function multiplies two numbers def multiply(x, y): return x * y # This function divides two numbers def divide(x, y): return x / y print("Select operation.") print("1.Add") print("2.Subtract") print("3.Multiply") print("4.Divide") # Take input from the user choice = input("Enter choice(1/2/3/4):") num1 = int(input("Enter first number: ")) num2 = int(input("Enter second number: ")) if choice == '1': print(num1,"+",num2,"=", add(num1,num2)) elif choice == '2': print(num1,"-",num2,"=", subtract(num1,num2)) elif choice == '3': print(num1,"*",num2,"=", multiply(num1,num2)) elif choice == '4': print(num1,"/",num2,"=", divide(num1,num2)) else: print("Invalid input")
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.