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
COMPLETE THE _CONSTRUCT() AND CONSTRUCTTREE() FUNCTIONS class expressionTree: class treeNode: def __init__(self, value, lchild, rchild):...
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 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...
class Bool(Expr): """A boolean constant literal. === Attributes === b: the value of the constant """ b: bool def __init__(self, b: bool) -> None: """Initialize a new boolean constant.""" self.b = b # TODO: implement this method! def evaluate(self) -> Any: """Return the *value* of this expression. The returned value should the result of how this expression would be evaluated by the Python interpreter. >>> expr = Bool(True) >>> expr.evaluate() True """ return self.b def __str__(self) -> str: """Return a...
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...
How do you do this? class Event: """A new calendar event.""" def __init__(self, start_time: int, end_time: int, event_name: str) -> None: """Initialize a new event that starts at start_time, ends at end_time, and is named name. Precondition: 0 <= start_time < end_time <= 23 >>> e = Event(12, 13, 'Lunch') >>> e.start_time 12 >>> e.end_time 13 >>> e.name 'Lunch' """ self.start_time = start_time self.end_time = end_time self.name = event_name def __str__(self) -> str: """Return a string representation of this...
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): 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, 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 # 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 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...