Pyhton 3. Based on the given code of Infix to Postfix conversion, add another fu
ID: 3719073 • Letter: P
Question
Pyhton 3.
Based on the given code of Infix to Postfix conversion, add another function/option for evaluation of the postfix expression. For example, if the user input the infix expression of A + B / C, so the user can evaluate the unknown of A, B and C into any integer or numbers.
class Stack: def init_ _(self) self.items = [] self.length 0 def push (self, val) self.items.append (val) self.length 1 def pop(self) if self.empty): return None self.length1 return self.items .pop) dlef size (self) return self.length def peek(self) if self.empty): return None return self.items [0] def empty(self) return self. length = 0 def tr (self) return str (self.items) precedence precedence [ ' * ' ] = 3 precedence-3 precedenceI'+'-2 precedence--2 precedence''] - 1 def convert (expression) print(__convert (expression.split O)) dlef convert (tokens): postfix -[1 opstack-Stack ) or token in tokens if token.isidentifier: postfix.append (token) opstack.push (token) while True: elif tokenC': elif token'': tempopstack pop) if temp is None or temp' brea elif not temp.isidentifier postfix.append (temp) else: # must be operator if not opstack.empty): temp opstack.peek) while not opstack .empty() and precedence [temp] precedence [token] and token. isidentifier(): >= postfix.append (opstack po) temp opstack.peek (0 opstack-push (token) while not opstack.empty) postfix.append (opstack pop O) return postfix s input ( 'Enter Infix expression : convert (s) ' ) ;Explanation / Answer
Just Change the Code For the Below Steps :
#Add This Method to your Program.....
# to postfix expression
def evaluatePostfix(self, exp):
# Iterate over the expression for conversion
for i in exp:
# If the scanned character is an operand
# (number here) push it to the stack
if i.isdigit():
self.push(i)
# If the scanned character is an operator,
# pop two elements from stack and apply it.
else:
val1 = self.pop()
val2 = self.pop()
self.push(str(eval(val2 + i + val1)))
return int(self.pop())
In convert(expression): method just call the evaluatePostfix method to evaluate the Posfix expression
print(evaluatePostfix(__convert(expression.split()))) juss replace this line in the convert method.
Made this two changes code will work for evaluation also.....
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.