Question: Python Code Only Problem Set 5b [20 points] For this assignment you are to take the parse tree that you made in Problem Set 5a,
Python Code Only
Problem Set 5b [20 points]
For this assignment you are to take the parse tree that you made in Problem Set 5a, as input and create and print a derivative tree. The derivative tree should be a binary tree with the nodes that contain the normal data, left, right, and parent fields.
The derivative of an expression that involves the variable x or X can be defined by a few recursive rules:
If A is an expression, let D(A) be the derivative of A.
The derivative of a constant is 0. D(C) = 0.
The derivative of x or X is 1. D(x) = D(X) = 1.
If A and B are expressions, let D(A) be the derivative of A and D(B) be the derivative of B. Then
1.The D(A + B) is D(A) + D(B).
2.The D(A - B) is D(A) - D(B).
3.The D(A * B) is (A * D(B)) + (B * D(A)).
4.The D(A / B) is ((B * D(A)) - (A * D(B))) / (B * B) [Extra Credit]
Heres my starter code. note that this is in python.
class ParseTree: def __init__(self, value): self.value = value
self.left = None
self.right = None
def isOperator(c): if (c == '+' or c == '-' or c == '*' or c == '/' or c == '^'): return True else: return False
def inorder(t): if t is not None: inorder(t.left) print (t.value) inorder(t.right)
def constructTree(postfix): stack = [] for char in postfix: if not isOperator(char): t = ParseTree(char) stack.append(t) else: t = ParseTree(char) t1 = stack.pop() t2 = stack.pop()
t.right = t1 t.left = t2
stack.append(t)
t = stack.pop() return t
postfix = "ab+ef*g*-" r = constructTree(postfix) print ("Infix expression is") inorder(r)
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
