Question: For this assignment you are to take the expression created by the derivative tree and simplify it using the following rules: E + 0 =

For this assignment you are to take the expression created by the derivative tree and simplify it using the following rules:

E + 0 = 0 + E = E * 1 = 1 * E = E - 0 = E or E / 1 (extra credit)

and

0 + 0 = 0 - 0 = E * 0 = 0 * E = 0 or 0 / E (!=0) (extra credit)

This is the derivative tree code by

# coding: utf-8

# In[91]:

parse = []

def D(t): parse[:] = [] inorder(t.right) t_right = "("+''.join(parse) + ")" parse[:] = [] inorder(t.left) t_left = "("+''.join(parse)+")"

if t.value in "0123456789": return 0 elif t.value in "x": return 1 elif t.value in "+": return D(t.left) + "+" + D(t.right) elif t.value in "-": return D(t.left) + "-" + D(t.right) elif t.value in "*": return "(" + t_left + " * " + D(t.right) + " ) + ( " + t_right + " * " + D(t.left) + " )" elif t.value == "/": return "((" + t_right + "*" + D(t.left) + ") - (" +t_left + "*" +D(t.right) + ") / (" + t_right + "*" + t_right + "))" else: return "(D "+t.value + ")" class Et: # Constructor to create a node

def __init__(self , value):

self.value = value

self.left = None

self.right = None

# A utility function to check if 'c'

# is an operator

def isOperator(c):

if (c == '+' or c == '-' or c == '*'

or c == '/' or c == '^'):

return True

else:

return False

# A utility function to do inorder traversal

def inorder(t):

if t is not None:

inorder(t.left) parse.append(t.value) inorder(t.right)

# Returns root of constructed tree for

# given postfix expression

def constructTree(postfix):

stack = []

# Traverse through every character of input expression

for char in postfix :

# if operand, simply push into stack

if not isOperator(char):

t = Et(char)

stack.append(t)

# Operator

else:

# Pop two top nodes

t = Et(char) t1 = stack.pop() t.right = t1 t2 = stack.pop() t.left = t2 # Add this subexpression to stack stack.append(t) # Only element will be the root of expression tree t = stack.pop() return t

# Driver program to test above

postfix = "ab+ef*g*-"

r = constructTree(postfix)

print("Infix expression is") inorder(r) print(parse)

r = constructTree(postfix) derivative = D(r) print("Derivative is") print(derivative)

I need this assignment to be written in python

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Databases Questions!