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).
*the expression stored in the binary tree is“1+(2*3)+3^ 2"*
For example: (OPERAND, 5), (OPERAND, 7), (OPERATOR, '*’').
Following operators should be supported: addition (+), subtraction (-), multiplication (*), and exponentiation .
*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 =* 100
(Should be print 100)
class Tree:
def __init__(S, N=None):
S.Q = []
if N:
S.Q.append(N)
S.globalflag = False
def E_node(S, N):
if N.is_leaf:
return float(N.value)
elif N.value == '+':
return S.E_node(N.left) + S.E_node(N.right)
elif N.value == '-':
return S.E_node(N.left) - S.E_node(N.right)
elif N.value == '*':
return S.E_node(N.left) * S.E_node(N.right)
elif N.value == '^':
return S.E_node(N.left) ** S.E_node(N.right)
def event(S):
while len(S.Q) > 1:
S.Q[1].left = S.Q[0]
S.Q[1].right = S.Q[2]
S.Q.pop(2)
S.Q.pop(0)
def display(S):
if len(S.Q) > 1:
S.event()
print(S.E_node(S.Q[0]))
def insert(S, data, flag):
if S.globalflag:
S.Q[-1].right = Node(data)
S.Q[-1].left = S.Q.pop(-2)
S.globalflag = False
else:
S.globalflag = flag
S.Q.append(Node(data))
return S
class Node:
def __init__(S, data, left=None, right=None):
S.is_leaf = data[0] == 'OPERAND'
S.value = data[1]
S.left = left
S.right = right
def __repr__(S):
return f'(value: {S.value}, left: {S.left}, right: {S.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.display()
Comments
Leave a comment