This assignment is about creating and using heaps. Implement a heap .docx
1. This assignment is about creating and using heaps. Implement
a heap using an array. Your heap class will have one private
attibute, an array of integers. Implement the following methods
for the heap class. init - Constructor makes an empty heap str
- Prints the heap out in any way you want (for debugging only)
makenull(self) - Makes the heap empty insert(self, x) - Insert
element x into the heap parent(self, i) - Returns the index of
the parent of the element at index i (p=(i-1)/2) left(self, i) -
Returns the index of the left child of the element at index i
(l=(i+1)*2-1 right(self.i) - Returns the index of the right child
of the element at index i (r=(i+1)*2) swap(self, a, b) - Swaps
elements at indexes a and b upheap(self, i) - Upheaps starting
at index i downheap(self, i) - Downheaps starting at index i
inorder(self.i) - Prints tree inorder starting at index i
preorder(self, i) - Prints tree in preorder starting at index i
postorder(self, i) - Prints tree in postorder starting at index i
min(self) - returns the smallest value in heap deletemin(self) -
deletes smallest number in heap Run your own tests when this
file is run as main to show your code works correctly. Next,
you will make a command line interface for the heap. There are
only three commands here that are not directly related to the
heap methods from above. sort - Call min/deletemin repeatedly
to print out the list in sorted order help - Print out the
instructions exit - Ends the program
Solution
#heap.py
class HeapImp:
myHeapAry = []
2. def __init_(self):
self.myHeapAry = []
def __str__(self):
strr = " ".join(str(y) for y in self.myHeapAry)
return strr
def makenull(self):
self.myHeapAry = []
def insert(self, x):
self.myHeapAry.append(x)
self.upheap(len(self.myHeapAry)-1)
def parent(self, i):
return int (i - 1) / 2
def left(self, i):
return int ((i + 1) * 2 - 1)
def right(self, i):
return int ((i + 1) * 2)
def swap(self, a, b):
temp = self.myHeapAry[a]
self.myHeapAry[a] = self.myHeapAry[b]
self.myHeapAry[b] = temp
5. print "Inorder Traversal:"
hp.inorder(0)
print "Preorder Traversal:"
hp.preorder(0)
print "Postorder Traversal:"
hp.postorder(0)
#main.py
import heap
hp=heap.HeapImp()
while True:
print "Menu"
print "1. sort"
print "2. help"
print "3. Exit"
t=int(raw_input("Enter your choice"))
if t==1:
while True:
hp.min();
hp.deletemin()
elif t==2:
print "The program is to show the operation of heap. You
can insert an element, delete a min element, traverse the heap"
else:
break