Question

Problem 3: Printing Expression Trees (15 points) Modify the function printexp given in chapter 6.7 your book (and hw6_tools.p

# Problem 3

def printexp(tree):
sVal = ""
if tree:
sVal = '(' + printexp(tree.getLeftChild())
sVal = sVal + str(tree.getRootVal())
sVal = sVal + printexp(tree.getRightChild())+')'
return sVal

#### Functions and classes to help with Homework 6

#### You should not make any changes to the functions and classes in this file,
#### but you should understand what they do and how they work.

import sys


### This function will be re-defined in hw6.py. However, it is needed for ExpTree,
### so it is redefined here as well. Do not modify this function, modify the
### one in hw6.py!
def printexp(tree):
sVal = ""
if tree:
sVal = '(' + printexp(tree.getLeftChild())
sVal = sVal + str(tree.getRootVal())
sVal = sVal + printexp(tree.getRightChild())+')'
return sVal


class ExpTree:
def __init__(self,key):
self.key = key
self.leftChild = None
self.rightChild = None

def setRightChild(self, child):
self.rightChild = child
def setLeftChild(self, child):
self.leftChild = child
def getRightChild(self):
return self.rightChild
def getLeftChild(self):
return self.leftChild

def setRootVal(self,obj):
self.key = obj
def getRootVal(self):
return self.key

def __str__(self):
sVal = printexp(self)
return sVal


class Graph:
def __init__(self):
self.vertices = {}
self.numVertices = 0

def addVertex(self,key):
self.numVertices = self.numVertices + 1
newVertex = Vertex(key)
self.vertices[key] = newVertex
return newVertex

def getVertex(self,n):
if n in self.vertices:
return self.vertices[n]
else:
return None

def __contains__(self,n):
return n in self.vertices

def addEdge(self,f,t,cost=0):
if f not in self.vertices:
nv = self.addVertex(f)
if t not in self.vertices:
nv = self.addVertex(t)
self.vertices[f].addNeighbor(self.vertices[t],cost)

def getVertices(self):
return list(self.vertices.keys())

def __iter__(self):
return iter(self.vertices.values())


class Vertex:
def __init__(self,num):
self.id = num
self.connectedTo = {}
self.color = 'white'
self.dist = sys.maxsize
self.pred = None
self.disc = 0
self.fin = 0

# def __lt__(self,o):
# return self.id < o.id

def addNeighbor(self,nbr,weight=0):
self.connectedTo[nbr] = weight

def setColor(self,color):
self.color = color

def setDistance(self,d):
self.dist = d

def setPred(self,p):
self.pred = p

def setDiscovery(self,dtime):
self.disc = dtime

def setFinish(self,ftime):
self.fin = ftime

def getFinish(self):
return self.fin

def getDiscovery(self):
return self.disc

def getPred(self):
return self.pred

def getDistance(self):
return self.dist

def getColor(self):
return self.color

def getConnections(self):
return self.connectedTo.keys()

def getWeight(self,nbr):
return self.connectedTo[nbr]

def __str__(self):
return str(self.id) + ":color " + self.color + ":disc " + str(self.disc) + ":fin " + str(self.fin) + ":dist " + str(self.dist) + ":pred \n\t[" + str(self.pred)+ "]\n"

def getId(self):
return self.id


class PriorityQueue:
def __init__(self):
self.heapArray = [(0,0)]
self.currentSize = 0

def buildHeap(self,alist):
self.currentSize = len(alist)
self.heapArray = [(0,0)]
for i in alist:
self.heapArray.append(i)
i = len(alist) // 2
while (i > 0):
self.percDown(i)
i = i - 1

def percDown(self,i):
while (i * 2) <= self.currentSize:
mc = self.minChild(i)
if self.heapArray[i][0] > self.heapArray[mc][0]:
tmp = self.heapArray[i]
self.heapArray[i] = self.heapArray[mc]
self.heapArray[mc] = tmp
i = mc

def minChild(self,i):
if i*2 > self.currentSize:
return -1
else:
if i*2 + 1 > self.currentSize:
return i*2
else:
if self.heapArray[i*2][0] < self.heapArray[i*2+1][0]:
return i*2
else:
return i*2+1

def percUp(self,i):
while i // 2 > 0:
if self.heapArray[i][0] < self.heapArray[i//2][0]:
tmp = self.heapArray[i//2]
self.heapArray[i//2] = self.heapArray[i]
self.heapArray[i] = tmp
i = i//2

def add(self,k):
self.heapArray.append(k)
self.currentSize = self.currentSize + 1
self.percUp(self.currentSize)

def delMin(self):
retval = self.heapArray[1][1]
self.heapArray[1] = self.heapArray[self.currentSize]
self.currentSize = self.currentSize - 1
self.heapArray.pop()
self.percDown(1)
return retval

def isEmpty(self):
if self.currentSize == 0:
return True
else:
return False

def decreaseKey(self,val,amt):
# this is a little wierd, but we need to find the heap thing to decrease by
# looking at its value
done = False
i = 1
myKey = 0
while not done and i <= self.currentSize:
if self.heapArray[i][1] == val:
done = True
myKey = i
else:
i = i + 1
if myKey > 0:
self.heapArray[myKey] = (amt,self.heapArray[myKey][1])
self.percUp(myKey)

def __contains__(self,vtx):
for pair in self.heapArray:
if pair[1] == vtx:
return True
return False


def dijkstra(aGraph,start):
pq = PriorityQueue()
start.setDistance(0)
pq.buildHeap([(v.getDistance(),v) for v in aGraph])
while not pq.isEmpty():
currentVert = pq.delMin()
for nextVert in currentVert.getConnections():
newDist = currentVert.getDistance() \
+ currentVert.getWeight(nextVert)
if newDist < nextVert.getDistance():
nextVert.setDistance( newDist )
nextVert.setPred(currentVert)
pq.decreaseKey(nextVert,newDist)

0 0
Add a comment Improve this question Transcribed image text
Answer #1

Explanation in code comment :

rest of the code is same, only the printexp is modified as asked

CODE :

# Problem 3
"""
def printexp(tree):
sVal = ""
if tree:
sVal = '(' + printexp(tree.getLeftChild())
sVal = sVal + str(tree.getRootVal())
sVal = sVal + printexp(tree.getRightChild())+')'
return sVal
"""
#### Functions and classes to help with Homework 6
#### You should not make any changes to the functions and classes in this file,
#### but you should understand what they do and how they work.

import sys


### This function will be re-defined in hw6.py. However, it is needed for ExpTree,
### so it is redefined here as well. Do not modify this function, modify the
### one in hw6.py!

"""
EXPLANATION : Instead of adding braces whenever each node is calculated , we only need to add braces
whenever an expression is being evaluated and after traversal of left and right child
Hence by addding the condition of adding braces before and after the evaulted expression
for a given tree only when non numeric data is encountered solves the problem
EX : Simplify the tree for one root and 2 child nodes
*
/ \
2 5
the output would be (2*5)
Hence first left child call is made - sVal = 2
then again left and right call for node 2 are made and returned
Then node data is added - sVal = 2*
then right child call is made - sVal = 2*5
then again left and right call for node 5 are made and returned
then we add braces before and after sVal - (sVal) = (2*5)
"""
def printexp(tree):
sVal = ""
if tree:
sVal = printexp(tree.getLeftChild())
sVal = sVal + str(tree.getRootVal())
sVal = sVal + printexp(tree.getRightChild())
if not str(tree.getRootVal()).isnumeric():
sVal = '(' + sVal + ')'
return sVal


class ExpTree:
def __init__(self,key):
self.key = key
self.leftChild = None
self.rightChild = None
  
def setRightChild(self, child):
self.rightChild = child
def setLeftChild(self, child):
self.leftChild = child
def getRightChild(self):
return self.rightChild
def getLeftChild(self):
return self.leftChild
  
def setRootVal(self,obj):
self.key = obj
def getRootVal(self):
return self.key
  
def __str__(self):
sVal = printexp(self)
return sVal


class Graph:
def __init__(self):
self.vertices = {}
self.numVertices = 0
  
def addVertex(self,key):
self.numVertices = self.numVertices + 1
newVertex = Vertex(key)
self.vertices[key] = newVertex
return newVertex
  
def getVertex(self,n):
if n in self.vertices:
return self.vertices[n]
else:
return None
  
def __contains__(self,n):
return n in self.vertices

def addEdge(self,f,t,cost=0):
if f not in self.vertices:
nv = self.addVertex(f)
if t not in self.vertices:
nv = self.addVertex(t)
self.vertices[f].addNeighbor(self.vertices[t],cost)

def getVertices(self):
return list(self.vertices.keys())

def __iter__(self):
return iter(self.vertices.values())


class Vertex:
def __init__(self,num):
self.id = num
self.connectedTo = {}
self.color = 'white'
self.dist = sys.maxsize
self.pred = None
self.disc = 0
self.fin = 0
  
# def __lt__(self,o):
# return self.id < o.id
  
def addNeighbor(self,nbr,weight=0):
self.connectedTo[nbr] = weight
  
def setColor(self,color):
self.color = color
  
def setDistance(self,d):
self.dist = d
  
def setPred(self,p):
self.pred = p
  
def setDiscovery(self,dtime):
self.disc = dtime
  
def setFinish(self,ftime):
self.fin = ftime
  
def getFinish(self):
return self.fin
  
def getDiscovery(self):
return self.disc
  
def getPred(self):
return self.pred
  
def getDistance(self):
return self.dist
  
def getColor(self):
return self.color
  
def getConnections(self):
return self.connectedTo.keys()
  
def getWeight(self,nbr):
return self.connectedTo[nbr]
  
def __str__(self):
return str(self.id) + ":color " + self.color + ":disc " + str(self.disc) + ":fin " + str(self.fin) + ":dist " + str(self.dist) + ":pred \n\t[" + str(self.pred)+ "]\n"
  
def getId(self):
return self.id
  

class PriorityQueue:
def __init__(self):
self.heapArray = [(0,0)]
self.currentSize = 0
  
def buildHeap(self,alist):
self.currentSize = len(alist)
self.heapArray = [(0,0)]
for i in alist:
self.heapArray.append(i)
i = len(alist) // 2
while (i > 0):
self.percDown(i)
i = i - 1

def percDown(self,i):
while (i * 2) <= self.currentSize:
mc = self.minChild(i)
if self.heapArray[i][0] > self.heapArray[mc][0]:
tmp = self.heapArray[i]
self.heapArray[i] = self.heapArray[mc]
self.heapArray[mc] = tmp
i = mc
  
def minChild(self,i):
if i*2 > self.currentSize:
return -1
else:
if i*2 + 1 > self.currentSize:
return i*2
else:
if self.heapArray[i*2][0] < self.heapArray[i*2+1][0]:
return i*2
else:
return i*2+1
  
def percUp(self,i):
while i // 2 > 0:
if self.heapArray[i][0] < self.heapArray[i//2][0]:
tmp = self.heapArray[i//2]
self.heapArray[i//2] = self.heapArray[i]
self.heapArray[i] = tmp
i = i//2

def add(self,k):
self.heapArray.append(k)
self.currentSize = self.currentSize + 1
self.percUp(self.currentSize)
  
def delMin(self):
retval = self.heapArray[1][1]
self.heapArray[1] = self.heapArray[self.currentSize]
self.currentSize = self.currentSize - 1
self.heapArray.pop()
self.percDown(1)
return retval

def isEmpty(self):
if self.currentSize == 0:
return True
else:
return False

def decreaseKey(self,val,amt):
# this is a little wierd, but we need to find the heap thing to decrease by
# looking at its value
done = False
i = 1
myKey = 0
while not done and i <= self.currentSize:
if self.heapArray[i][1] == val:
done = True
myKey = i
else:
i = i + 1
if myKey > 0:
self.heapArray[myKey] = (amt,self.heapArray[myKey][1])
self.percUp(myKey)

def __contains__(self,vtx):
for pair in self.heapArray:
if pair[1] == vtx:
return True
return False


def dijkstra(aGraph,start):
pq = PriorityQueue()
start.setDistance(0)
pq.buildHeap([(v.getDistance(),v) for v in aGraph])
while not pq.isEmpty():
currentVert = pq.delMin()
for nextVert in currentVert.getConnections():
newDist = currentVert.getDistance() \
+ currentVert.getWeight(nextVert)
if newDist < nextVert.getDistance():
nextVert.setDistance( newDist )
nextVert.setPred(currentVert)
pq.decreaseKey(nextVert,newDist)


rl2 = ExpTree(5)
rr2 = ExpTree(2)
rr1 = ExpTree('-')
ll3 = ExpTree(1)
lr3 = ExpTree(2)
lr2 = ExpTree('/')
ll2 = ExpTree(3)
ll1 = ExpTree('+')
r = ExpTree('*')
r.setLeftChild(ll1)
r.setRightChild(rr1)
ll1.setLeftChild(ll2)
ll1.setRightChild(lr2)
lr2.setLeftChild(ll3)
lr2.setRightChild(lr3)
rr1.setLeftChild(rl2)
rr1.setRightChild(rr2)
print(str(r))

ktuzzy Spyder (Python 3.J) Eile Edit Searh So un Debug Consales Projects Tools View Help Var able espkre NameType Size 15 inpktuzzy Spyder (Python 3.J) Eile Edit Searh So un Debug Consales Projects Tools View Help Var able espkre NameType Size 58 claktuzzy Spyder (Python 3.J) Eile Edit Searh So un Debug Consales Projects Tools View Help Var able espkre Crapeack.py X Natriektuzzy Spyder (Python 3.J) Eile Edit Searh So un Debug Consales Projects Tools View Help Var able espkre NameType Size 90 retktuzzy Spyder (Python 3.J) Eile Edit Searh So un Debug Consales Projects Tools View Help Var able espkre NameType Size 129 sektuzzy Spyder (Python 3.J) Eile Edit Searh So un Debug Consales Projects Tools View Help Var able espkre Crapeack.py X NameTyktuzzy Spyder (Python 3.J) Eile Edit Searh So un Debug Consales Projects Tools View Help Var able espkre Natrie. Type . Sizektuzzy Spyder (Python 3.J) Eile Edit Searh So un Debug Consales Projects Tools View Help Var able espkre Crapeack.py X NameTyktuzzy Spyder (Python 3.J) Eile Edit Searh So un Debug Consales Projects Tools View Help Var able espkre Natrie. Type . Size| In [23]: runfile(C:/users/Rogue/Desktop/knapsack . py, wdr=c:/Users/Rogue/ Desktop) In [24]: runfile(C:/Users/Rogue/De

Add a comment
Know the answer?
Add Answer to:
# Problem 3 def printexp(tree): sVal = "" if tree: sVal = '(' + printexp(tree.getLeftChild()) sVal = sV...
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 QUESTION... Building a Binary Tree with extended Binary Search Tree and AVL tree. Create a...

    PYTHON QUESTION... Building a Binary Tree with extended Binary Search Tree and AVL tree. Create a class called MyTree with the methods __init__(x), getLeft(), getRight(), getData(), insert(x) and getHeight(). Each child should itself be a MyTree object. The height of a leaf node should be zero. The insert(x) method should return the node that occupies the original node's position in the tree. Create a class called MyBST that extends MyTree. Override the method insert(x) to meet the definitions of a...

  • 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...

  • 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")...

  • 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...

  • want to create a prefix tree in python (3) 2 ADTs Node and PrefixTree Looking to...

    want to create a prefix tree in python (3) 2 ADTs Node and PrefixTree Looking to create Node class with : -__contains__(letter) - returns true if the Node has a child corresponding to the letter -__getitem__(let) - returns the child node corresponding to the letter -add_sub(tok, value) - adds a child to the node under the given token, also handle the case if a child already exists (it should only change the value of the child) -remove_sub(let) - removes the...

  • PYTHON. Continues off another code. I don't understand this. Someone please help! Comment the lines please...

    PYTHON. Continues off another code. I don't understand this. Someone please help! Comment the lines please so I can understand LinkedList ADT: class myLinkedList:     def __init__(self):         self.__head = None         self.__tail = None         self.__size = 0     def insert(self, i, data):         if self.isEmpty():             self.__head = listNode(data)             self.__tail = self.__head         elif i <= 0:             self.__head = listNode(data, self.__head)         elif i >= self.__size:             self.__tail.setNext(listNode(data))             self.__tail = self.__tail.getNext()         else:             current = self.__getIthNode(i - 1)             current.setNext(listNode(data,...

  • YOU NEED TO MODIFY THE PROJECT INCLUDED AT THE END AND USE THE INCLUDED DRIVER TO...

    YOU NEED TO MODIFY THE PROJECT INCLUDED AT THE END AND USE THE INCLUDED DRIVER TO TEST YOUR CODE TO MAKE SURE IT WORK AS EXPECTED. Thanks USING PYTHON, complete the template below such that you will provide code to solve the following problem: Please write and/or extend the project5 attached at the end. You will have to do the following for this assignment: Create and complete the methods of the PriceException class. Create the processFile function. Modify the main...

  • Python code that sorts books

    class Book:    def __init__(self,id,bookName,authorName,nextNode=None):         self.id = id         self.bookName = bookName         self.authorName = authorName         self.nextNode = nextNode    def getId(self):        return self.id     def getBookName(self):        return self.bookName    def getAuthorName(self):        return self.authorName    def getNextNode(self):        return self.nextNode       def setNextNode(self,val):         self.nextNode = val   class LinkedList:    def __init__(self,head = None):         self.head = head         self.size = 0     def getSize(self):        return self.size    def AddBookToFront(self,newBook):         newBook.setNextNode(self.head)         self.head = newBook         self.size+=1     def DisplayBook(self):         curr = self.head        while curr:            print(curr.getId(),curr.getBookName(),curr.getAuthorName())              curr = curr.getNextNode()    def RemoveBookAtPosition(self,n):         prev = None         curr = self.head         curPos = 0         while curr:            if curPos == n:                if prev:                     prev.setNextNode(curr.getNextNode())                else:                     self.head = curr.getNextNode()                 self.size = self.size - 1                 return True                  prev = curr             curr = curr.getNextNode()              curPos = curPos + 1          return False     def AddBookAtPosition(self,newBook,n):         curPos = 1         if n == 0:             newBook.setNextNode(self.head)             self.head = newBook             self.size+=1             return         else:             currentNode = self.head            while currentNode.getNextNode() is not None:                if curPos == n:                     newBook.setNextNode(currentNode.getNextNode())                     currentNode.setNextNode(newBook)                     self.size+=1                     return                 currentNode = currentNode.getNextNode()                 curPos = curPos + 1             if curPos == n:                 newBook.setNextNode(None)                 currentNode.setNextNode(newBook)                 self.size+=1             else:                print("cannot add",newBook.getId(),newBook.getBookName(),"at that position")    def SortByAuthorName(self):        for i in range(1,self.size):             node1 = self.head             node2 = node1.getNextNode()            while node2 is not None:                if node1.authorName > node2.authorName:                     temp = node1.id                     temp2 = node1.bookName                     temp3 = node1.authorName                     node1.id = node2.id                     node1.bookName = node2.bookName                     node1.authorName = node2.authorName                     node2.id = temp                     node2.bookName = temp2                     node2.authorName = temp3                 node1 = node1.getNextNode()                 node2 = node2.getNextNode()     myLinkedList = LinkedList() nodeA = Book("#1","cool","Isaac") nodeB = Book("#2","amazing","Alfred") nodeC = Book("#3","hello","John") nodeD = Book("#4","why","Chase") nodeE = Book("#5","good","Mary") nodeF = Book("#6","hahaha","Radin") myLinkedList.AddBookToFront(nodeA) myLinkedList.AddBookToFront(nodeB) myLinkedList.AddBookToFront(nodeC) myLinkedList.AddBookAtPosition(nodeD,1) myLinkedList.AddBookAtPosition(nodeE,1) myLinkedList.AddBookAtPosition(nodeF,1) myLinkedList.RemoveBookAtPosition(2) myLinkedList.RemoveBookAtPosition(2) myLinkedList.DisplayBook() myLinkedList.SortByAuthorName()print(myLinkedList.getSize())...

  • PYTHON. Continues off another code(other code is below). I don't understand this. Someone please help! Comment...

    PYTHON. Continues off another code(other code is below). I don't understand this. Someone please help! Comment the lines please so I can understand. There are short and med files lengths for each the list of names/ids and then search id file. These are the input files: https://codeshare.io/aVQd46 https://codeshare.io/5M3XnR https://codeshare.io/2W684E https://codeshare.io/5RJwZ4 LinkedList ADT to store student records(code is below). Using LinkedList ADT instead of the Python List. You will need to use the Student ADT(code is below) Imports the Student class...

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