In: Computer Science
from MyStack import MyStack
def infixToPostfix(infixexpr):
prec = {}
prec["*"] = 3
prec["/"] = 3
prec["+"] = 2
prec["-"] = 2
prec["("] = 1
opStack = Stack()
postfixList = []
tokenList = infixexpr.split()
for token in tokenList:
if token in "ABCDEFGHIJKLMNOPQRSTUVWXYZ" or token in "0123456789":
postfixList.append(token)
elif token in prec:
op_2=operand_stack.peek()
operand_stack.pop()
op_1=operand_stack.peek()
operand_stack.pop()
operand_stack.push("("+op_1+token+op_2+")")
temporary_list.append(operand_stack.pop())
for i in temporary_list[0]:
infix_list.append(i)
return " ".join(infix_list)
print(postfix_to_infix("3 6 7*+"))
def doMath(op, op1, op2):
if op == "*":
return op1 * op2
elif op == "/":
return op1 / op2
elif op == "+":
return op1 + op2
else:
return op1 - op2
def infixEval(expr):
operandStack=MyStack()
operatorStack=MyStack
tokenList=expr.split()
for token in tokenList:
if token in "1234567890":
operandStack.push(int(token))
elif token in"*/+-":
operatorStack.push(int(token))
elif token== "(":
continue
elif token==")":
operand2=operandStack.pop()
operand1=operandStack.pop()
operator=operatorStack.pop()
result=doMath(operator,operand1, operand2)
operandStack.push(result)
return operandStack.pop()
print(infixEval("(3+(8*1))"))
Turn this direct infix evaluator from the above problem into a calculator.
Python
def calc():
print("Select an operation.")
print("1.Add , 2.Subtract , 3.Multiply , 4.Divide")
while True:
# Take input
choice = input("Enter your choice of operation (1/2/3/4): ")
# Check whether the choice is one of the defined options
if (choice in ('1', '2', '3', '4')):
num1 = float(input("Enter first number: "))
num2 = float(input("Enter second number: "))
num1 = str(num1)
num2 = str(num2)
if (choice == '1'):
print(infixEval(num1+"+"+num2))
elif choice == '2':
print(infixEval(num1+"-"+num2))
elif choice == '3':
print(infixEval(num1+"*"+num2))
elif choice == '4':
print(infixEval(num1+"/"+num2))
break
else :
print("Invalid Input")
calc()