Answered step by step
Verified Expert Solution
Link Copied!

Question

1 Approved Answer

Using PYTHON Turn the code below into a calculator to evaluate an infix result. You should read 2 operands and an operation, form an infix

Using PYTHON

Turn the code below into a calculator to evaluate an infix result. You should read 2 operands and an operation, form an infix expression then evaluate it by first passing it to infix_to_postfix() and then passing the result to postfix_eval() to obtain the result.

import stack def infix_to_postfix(infix_expr): prec = {} prec["*"] = 3 prec["/"] = 3 prec["+"] = 2 prec["-"] = 2 prec["("] = 1 op_stack = stack.Stack() postfix_list = [] token_list = infix_expr.split() for token in token_list: if token in "ABCDEFGHIJKLMNOPQRSTUVWXYZ" or token in "0123456789": postfix_list.append(token) elif token == "(": op_stack.push(token) elif token == ")": top_token = op_stack.pop() while top_token != "(": postfix_list.append(top_token) top_token = op_stack.pop() else: while (not op_stack.is_empty()) and (prec[op_stack.peek()] >= prec[token]): postfix_list.append(op_stack.pop()) op_stack.push(token) while not op_stack.is_empty(): postfix_list.append(op_stack.pop()) return " ".join(postfix_list) def postfix_eval(postfix_expr): operand_stack = stack.Stack() token_list = postfix_expr.split() for token in token_list: if token in "0123456789": operand_stack.push(int(token)) else: operand2 = operand_stack.pop() operand1 = operand_stack.pop() result = do_math(token, operand1, operand2) operand_stack.push(result) return operand_stack.pop() def do_math(op, op1, op2): if op == "*": return op1 * op2 elif op == "/": return op1 / op2 elif op == "+": return op1 + op2 else: return op1 - op2 # add code to turn this into an infix evaluator 

infix_to_postfix(" 1 + 1 ") postfix_eval("1 1 +")

Step by Step Solution

There are 3 Steps involved in it

Step: 1

blur-text-image

Get Instant Access to Expert-Tailored Solutions

See step-by-step solutions with expert insights and AI powered tools for academic success

Step: 2

blur-text-image

Step: 3

blur-text-image

Ace Your Homework with AI

Get the answers you need in no time with our AI-driven, step-by-step assistance

Get Started

Recommended Textbook for

Fundamentals Of Database Management Systems

Authors: Mark L. Gillenson

3rd Edition

978-1119907466

More Books

Students also viewed these Databases questions

Question

Provide examples of KPIs in Human Capital Management.

Answered: 1 week ago

Question

What are OLAP Cubes?

Answered: 1 week ago