Question

COMPLETE THE _CONSTRUCT() AND CONSTRUCTTREE() FUNCTIONS class expressionTree:    class treeNode: def __init__(self, value, lchild, rchild):...

COMPLETE THE _CONSTRUCT() AND CONSTRUCTTREE() FUNCTIONS

class expressionTree:
  
class treeNode:
def __init__(self, value, lchild, rchild):
self.value, self.lchild, self.rchild = value, lchild, rchild

def __init__(self):
self.treeRoot = None

  
#utility functions for constructTree
def mask(self, s):
nestLevel = 0
masked = list(s)
for i in range(len(s)):
if s[i]==")":
nestLevel -=1
elif s[i]=="(":
nestLevel += 1
if nestLevel>0 and not (s[i]=="(" and nestLevel==1):
masked[i]=" "
return "".join(masked)
def isNumber(self, expr):
mys=s.strip()
if len(mys)==0 or not isinstance(mys, str):
print("type mismatch error: isNumber")
return "type mismatch error: isNumber"
try:
float(mys)
return True
except:
return False
def _construct(self,expr):
# First strip expr
# If isNumber(expr) is true, it's a leaf.
# Otherwise
# - do s = mask(expr)
# - find an operator of the lowest precedence in s
# - If there is no operator in s,
# and s[0]="(", s[len(s)-1]=")"
# remove the outermost parenthese and pass the rest
# to _constrct recursively
# - otherwise pos = position of the discovered operator
# pass expr[:pos] and expr[pos+1:]
# to _constrct recursively
# - Create a new treeNode
# - Connect the three to return the root
expr=expr.strip()
if expr=="":
return None
elif self.isNumber(expr):
return self.treeNode(expr, None, None)
else:
#--- code the rest ----

#Build the expression tree at self.treeRoot
def constructTree(self, expr):
# code one line to set self.treeRoot using _construct


# To check your constructTree
e = expressionTree()
expr =" 5*(2 / (3-1)) - (-1)*( 4 - 5*( 6- 3^(2-5) ) ) + 5 "
e.constructTree(expr)

# The pseudo code in the lecture notes modified
def getExpr(root):
TL, TR = root.lchild, root.rchild
if TL==None and TR==None:
r = str(root.value)
if float(r)<0:
return "(" + r + ")"
else:
return r
else:
if TL==None:
L = ""
elif (root.value=="*" or root.value=="/" or root.value=="^") and (TL.value=="+" or TL.value=="-"):
L = "(" + getExpr(TL) + ")"
else:
L = getExpr(TL)
if TR==None:
R = ""
elif (root.value=="*" or root.value=="/" or root.value=="^") and (TR.value=="+" or TR.value=="-"):
R = "(" + getExpr(TR) + ")"
else:
R = getExpr(TR)
return L + str(root.value) + R
  
## This should print
#5*2/(3-1)-(-1)*(4-5*(6-3^(2-5)))+5

1 0
Add a comment Improve this question Transcribed image text
Know the answer?
Add Answer to:
COMPLETE THE _CONSTRUCT() AND CONSTRUCTTREE() FUNCTIONS class expressionTree:    class treeNode: def __init__(self, value, lchild, rchild):...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • PYTHON -------------------------------------------------------- class LinkedList:    def __init__(self):        self.__head = None        self.__tail = None   

    PYTHON -------------------------------------------------------- class LinkedList:    def __init__(self):        self.__head = None        self.__tail = None        self.__size = 0    # Return the head element in the list    def getFirst(self):        if self.__size == 0:            return None        else:            return self.__head.element        # Return the last element in the list    def getLast(self):        if self.__size == 0:            return None        else:            return self.__tail.element    # Add an element to the beginning of the list    def addFirst(self, e):        newNode = Node(e) # Create a new node        newNode.next = self.__head # link...

  • in python and according to this #Creating class for stack class My_Stack: def __init__(self): self.items = [] def isEmpty(self): return self.items == [] def Push(self, d): self.items.append(d) def Po...

    in python and according to this #Creating class for stack class My_Stack: def __init__(self): self.items = [] def isEmpty(self): return self.items == [] def Push(self, d): self.items.append(d) def Pop(self): return self.items.pop() def Display(self): for i in reversed(self.items): print(i,end="") print() s = My_Stack() #taking input from user str = input('Enter your string for palindrome checking: ') n= len(str) #Pushing half of the string into stack for i in range(int(n/2)): s.Push(str[i]) print("S",end="") s.Display() s.Display() #for the next half checking the upcoming string...

  • Python 3+ Adjust the following code so the two errors below are non-present: 1. __init__() :...

    Python 3+ Adjust the following code so the two errors below are non-present: 1. __init__() : Since Pizza object don't have it's own set() datastructure, the toppings in the pizza object are manimupated from out of the object. (-1.0) 2. __eq__() : How about "self.toppings == other.toppings" rather than "self.toppings - other.toppin == set())". Code: ## Program 1 ## --------------------------------- class Pizza: def __init__(self, s='M', top=set()): self.setSize(s) self.toppings = top def setSize(self, s): self.size = s def getSize(self): return self.size...

  • Previous code: class BinarySearchTree: def __init__(self, data): self.data = data self.left = None self.right = None de...

    Previous code: class BinarySearchTree: def __init__(self, data): self.data = data self.left = None self.right = None def search(self, find_data): if self.data == find_data: return self elif find_data < self.data and self.left != None: return self.left.search(find_data) elif find_data > self.data and self.right != None: return self.right.search(find_data) else: return None    def get_left(self): return self.left def get_right(self): return self.right def set_left(self, tree): self.left = tree def set_right(self, tree): self.right = tree def set_data(self, data): self.data = data def get_data(self): return self.data def traverse(root,order):...

  • ill thumb up do your best python3 import random class CardDeck: class Card: def __init__(self, value):...

    ill thumb up do your best python3 import random class CardDeck: class Card: def __init__(self, value): self.value = value self.next = None def __repr__(self): return "{}".format(self.value) def __init__(self): self.top = None def shuffle(self): card_list = 4 * [x for x in range(2, 12)] + 12 * [10] random.shuffle(card_list) self.top = None for card in card_list: new_card = self.Card(card) new_card.next = self.top self.top = new_card def __repr__(self): curr = self.top out = "" card_list = [] while curr is not None:...

  • PYTHON: Conan is writing a module to contain different implementations of trees. After his first tree,...

    PYTHON: Conan is writing a module to contain different implementations of trees. After his first tree, the BinaryTreeclass, he wrote test code and is having problems understanding the error. Locate his problem and explain how you would fix it. class Node(object): def __init__(self, data=None): self.data = data def __str__(self): return "NODE: " + str(self.data)    class Tree(object): def __init__(self): self.root_node = None self.size = 0    def __len__(self): return self.size    def add(self, data): raise NotImplementedError("Add method not implemented.")    def inorder_traversal(self): raise NotImplementedError("inorder_traversal...

  • # Declaring Node class class Node: def __init__(self, node_address): self.address = node_address self.next = None #...

    # Declaring Node class class Node: def __init__(self, node_address): self.address = node_address self.next = None # Creating empty list forwarding_list = Node() # Recurssive Method for add address def addAddress(node): if node.address == old_address: # Address is same if node.next == None: # Next is None node.next = Node(new_address) # Add Next print("Added") # Addedd else: # Next is not none print("Entry already exists") elif node.next != None: # Check Next Node addAddress(node.next, old_address, new_address) def addEntry(forwarding_list):# Method for add...

  • class BinaryTree: def __init__(self, data, left=None, right=None): self.__data = data self.__left = left self.__right = right...

    class BinaryTree: def __init__(self, data, left=None, right=None): self.__data = data self.__left = left self.__right = right def insert_left(self, new_data): if self.__left == None: self.__left = BinaryTree(new_data) else: t = BinaryTree(new_data, left=self.__left) self.__left = t def insert_right(self, new_data): if self.__right == None: self.__right = BinaryTree(new_data) else: t = BinaryTree(new_data, right=self.__right) self.__right = t def get_left(self): return self.__left def get_right(self): return self.__right def set_data(self, data): self.__data = data def get_data(self): return self.__data def set_left(self, left): self.__left = left def set_right(self, right): self.__right...

  • Can you complete the following code, please? Thank you. class BinaryNode: def __init__(self, valu...

    Can you complete the following code, please? Thank you. class BinaryNode: def __init__(self, value): self.__value = value self.__left = None self.__right = None self.__parent = None self.__height = 1    def getValue(self): return self.__value    def setHeight(self, height): self.__height = height    def getHeight(self): return self.__height    def setParent(self, node): self.__parent = node    def getParent(self): return self.__parent    def setLeftChild(self, child): self.__left = child child.setParent(self)    def setRightChild(self, child): self.__right = child child.setParent(self)    def createLeftChild(self, value): self.__left = BinaryNode(value)    def createRightChild(self, value): self.__right = BinaryNode(value)    def...

  • class Population: def __init__(self, m=0, n=0, k=0): # 1 self.m = m self.n = n self.k...

    class Population: def __init__(self, m=0, n=0, k=0): # 1 self.m = m self.n = n self.k = k self.encounter = 0 bac = [] bac = bac + [1] * self.m + [2] * self.n + [3] * self.k self.bac = bac def plasmids(self): # 2 set = (self.m, self.n, self.k) return set def __str__(self): # 3 return "type I: {}, type II: {}, type III: {} (after {} encounters)".format(self.m, self.n, self.k, self.encounter) def __repr__(self): # 4 return "Population({}, {},...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT