You are required to implement a simple symbolic equation solver. The equation must be stored in a binary tree.
Each operand or operator should be stored as a tuple of the form (TYPE, VALUE).
For example: (OPERAND, 5), (OPERAND, 7), (OPERATOR, '*’').
Following operators should be supported: addition (+), subtraction (-), multiplication (*), and exponentiation .
Skeleton of this lab is given belo. Complete the bodies of the insert, and evaluate methods. Include your solution in the sections
*Input*
root = Node(('OPERAND', 1))
root = root.insert(('OPERATOR', '+'), False)
root = root.insert(('OPERAND', 2), False)
root = root.insert(('OPERATOR', '*'), True)
root = root.insert(('OPERAND', 3), False)
root = root.insert(('OPERATOR', '+'), False)
root = root.insert(('OPERAND', 3), False)
root = root.insert(('OPERATOR', '^'), False)
root = root.insert(('OPERAND', 2), False)
root.get_output()
*Expected output* = 100
class Tree:
def __init__(self, node=None):
self.queue = []
if node:
self.queue.append(node)
self.globalflag = False
def eval_node(self, node):
if node.is_leaf:
return float(node.value)
elif node.value == '+':
return self.eval_node(node.left) + self.eval_node(node.right)
elif node.value == '-':
return self.eval_node(node.left) - self.eval_node(node.right)
elif node.value == '*':
return self.eval_node(node.left) * self.eval_node(node.right)
elif node.value == '^':
return self.eval_node(node.left) ** self.eval_node(node.right)
def process_queue(self):
while len(self.queue) > 1:
self.queue[1].left = self.queue[0]
self.queue[1].right = self.queue[2]
self.queue.pop(2)
self.queue.pop(0)
def get_output(self):
if len(self.queue) > 1:
self.process_queue()
print(self.eval_node(self.queue[0]))
def insert(self, data, flag):
if self.globalflag:
self.queue[-1].right = Node(data)
self.queue[-1].left = self.queue.pop(-2)
self.globalflag = False
else:
self.globalflag = flag
self.queue.append(Node(data))
return self
class Node:
def __init__(self, data, left=None, right=None):
self.is_leaf = data[0] == 'OPERAND'
self.value = data[1]
self.left = left
self.right = right
def __repr__(self):
return f'(value: {self.value}, left: {self.left}, right: {self.right})'
root = Tree(Node(('OPERAND', 1)))
root = root.insert(('OPERATOR', '+'), False)
root = root.insert(('OPERAND', 2), False)
root = root.insert(('OPERATOR', '*'), True)
root = root.insert(('OPERAND', 3), False)
root = root.insert(('OPERATOR', '+'), False)
root = root.insert(('OPERAND', 3), False)
root = root.insert(('OPERATOR', '^'), False)
root = root.insert(('OPERAND', 2), False)
root.get_output()
Comments
Leave a comment