Question

Implement the class MaxHeapPriorityQueue as a heap with the following operations using python: - ...

Implement the class MaxHeapPriorityQueue as a heap with the following operations using python:

- MaxHeapPriorityQueue() creates a new heap that is empty. It needs no parameters and returns nothing.

- parent(index) returns the value of the parent of heap[index]. index is between 1 and the size of the heap. If index<=1 or index>size of the heap, it returns None

- leftChild(index) returns the value of the left child of heap[index], returns None if there is no value

- rightChild(index) returns the value of the right child of heap[index], return None if there is no value

- len(heap_object) returns the number of items in the heap. It needs no parameters and returns an integer.

- insert(item) adds the item into the heap satisfying the max heap property. It modifies self.heap and returns nothing. You can use the swap function provided in the starter code

- deleteMax() removes the max element of the heap (the root node). It needs no parameters and returns the value removed from the heap. The heap satisfies the max heap property after deletion. (If you think on a recursive approach, you are allowed to create another method to help this method restore the max heap property)

Provided methods:

def swap(self, index1, index2):
self.heap[index1-1], self.heap[index2-1] = self.heap[index2-1], self.heap[index1-1]

def deleteMax(self):

if self.size<=0:
return None
elif self.size==1:
self.size=0
return self.heap[0]

0 0
Add a comment Improve this question Transcribed image text
Answer #1
# class that represents a minHeap
class MaxHeapPriorityQueue:

        # algorithm:
        # we will store the nodes of the heap in a list
        # starting from 1st index.
        # a node at index i, will have its children at index 2*i + 1 
        # and 2*i + 2 indices.
        
        # constructor
        def __init__(self):
                self.heap = [0]
                self.currentSize = 0

        def parent(self, index):
                if index <= 1 or index > self.currentSize:
                        return None
                return self.heap[index // 2]

        def leftChild(self, index):
                l = index * 2
                if l <= 1 or l >= self.currentSize:
                        return None
                return self.heap[l]


        def rightChild(self, index):
                r = 1 + index * 2
                if r <= 1 or r >= self.currentSize:
                        return None
                return self.heap[r]

        def __len__(self):
                return self.currentSize

        def swap(self, index1, index2):
                self.heap[index1], self.heap[index2] = self.heap[index2], self.heap[index1]

        def deleteMax(self):
                if self.currentSize<=0:
                        return None
                else:
                        # remove the root node.
                        retval = self.heap[1]
                        self.heap[1] = self.heap[self.currentSize]
                        self.currentSize = self.currentSize - 1
                        self.heap.pop()
                        self.percDown(1)
                        return retval
        
        # this method bubblesUp the heap starting from a index till root
        def percUp(self, i):
                while self.parent(i) is not None:
                        if self.heap[i] > self.heap[i // 2]:
                                self.swap(i//2, i)
                        else:
                                break
                        i = i // 2

        # add a new entry to the heap
        def insert(self, k):
                self.heap.append(k)
                self.currentSize = self.currentSize + 1
                self.percUp(self.currentSize)
        
        # this method bubblesDown the heap starting from a index till leaf
        def percDown(self, i):
                while (i * 2) <= self.currentSize:
                        mc = self.maxChildIdx(i)
                        if self.heap[i] < self.heap[mc]:
                                self.swap(mc, i)
                        else:
                                break
                        i = mc

        # this method finds the index of the child having more values.
        def maxChildIdx(self, i):
                if self.rightChild(i) is None:
                        return i * 2
                else:
                        if self.leftChild(i) > self.rightChild(i):
                                return i * 2
                        else:
                                return i * 2 + 1

        # return number of entries in heap
        def len(self):
                return self.currentSize


hp = MaxHeapPriorityQueue()

for x in [10,7,12,6,3,8,17]:
        hp.insert(x)


while len(hp) != 0:
        print(hp.deleteMax())

Fles saved main.py 73 74 75 76 https://WhitesmokeDualAc else: D main.py break Python 3.6.1 (default, [GCC 4.8.2] on linux 17


Please upvote, as i have given the exact answer as asked in question. Still in case of any concerns in code, let me know in comments. Thanks!

Add a comment
Know the answer?
Add Answer to:
Implement the class MaxHeapPriorityQueue as a heap with the following operations using python: - ...
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
  • Implement the class MaxHeapPriorityQueue as a heap with the following operations: • MaxHeapPriorityQueue() creates a new...

    Implement the class MaxHeapPriorityQueue as a heap with the following operations: • MaxHeapPriorityQueue() creates a new heap that is empty. It needs no parameters and returns nothing. Note that as discussed in the video lecture, the index range of the array implementation of a heap is 1:n, NOT 0:n-1 • parent(index) returns the value of the parent of heap[index]. index is between 1 and the size of the heap. If index<=1 or index>size of the heap, it returns None •...

  • Min heap class implementation in Python. Implement a min-using an array. Your min-heap class will have...

    Min heap class implementation in Python. Implement a min-using an array. Your min-heap class will have one private attribute, an array of integers. Implement the following methods for the min-heap class You may not use the built-in min function. 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...

  • add/ remove any methods to the program. please post new code and output Min Heap: public...

    add/ remove any methods to the program. please post new code and output Min Heap: public class MinHeap { private int[] Heap; private int size; private int maxsize; private static final int FRONT = 1; public MinHeap(int maxsize) { this.maxsize = maxsize; this.size = 0; Heap = new int[this.maxsize + 1]; Heap[0] = Integer.MIN_VALUE; } private int parent(int pos) { return pos / 2; } private int leftChild(int pos) { return (2 * pos); } private int rightChild(int pos) {...

  • I need help Writing a Python code!!! Implement an ordered list using doubly linked list Implement...

    I need help Writing a Python code!!! Implement an ordered list using doubly linked list Implement the following operations for an ordered list of integers ordered in ascending order using a doubly linked list. The “head” of the list be where the “smallest items are and let “tail” be where the largest items are. You may use whatever mechanism you like to keep track of the head and tail of the list. E.g. references or sentinel nodes. • OrderedList ()...

  • 1. Code a breadth First traversal. 2. Code a depth First traversal. Note, your traversals should return a string listing...

    1. Code a breadth First traversal. 2. Code a depth First traversal. Note, your traversals should return a string listing the nodes added to the min spanning tree and the order they are added. Using Python. Starter code: from collections import deque class Edge: def __init__(self, endIndex, next = None): self.endIndex = endIndex self.next = next class Node: def __init__(self, name): self.name = name self.visited = False self.connects = None class Graph: def __init__(self): self.nodeList = [] self.size = 20...

  • Discrete Math Max Heap After you build your heap, you then compare the values of the vertices, in the following way: If a child of a parent node is larger than the parent node, switch their posit...

    Discrete Math Max Heap After you build your heap, you then compare the values of the vertices, in the following way: If a child of a parent node is larger than the parent node, switch their positions. Using the list above, the following operations would take place: The parent of value 4 would swap with child of value 8. 1. 8 4 Now the parent value of 4 would swap places with the child value of 6. 2. 6 2...

  • Write a second constructor that could be added to the HeapPriorityQueue class. This constructor accepts an...

    Write a second constructor that could be added to the HeapPriorityQueue class. This constructor accepts an array of elements as a parameter and uses that array as the heap rather than creating a new array. Of course, the array passed in is probably not in proper heap ordering, so you must rearrange it until it is. There's a neat trick for achieving this: If you just "bubble down" all of the non-leaf nodes of the heap, starting from the last...

  • Write a second constructor that could be added to the HeapPriorityQueue class. This constructor accepts an...

    Write a second constructor that could be added to the HeapPriorityQueue class. This constructor accepts an array of elements as a parameter and uses that array as the heap rather than creating a new array. Of course, the array passed in is probably not in proper heap ordering, so you must rearrange it until it is. There's a neat trick for achieving this: If you just "bubble down" all of the non-leaf nodes of the heap, starting from the last...

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

  • A test harness program for testing sorting methods is provided with the rest of the textbook...

    A test harness program for testing sorting methods is provided with the rest of the textbook program files. It is the file Sorts.java in the ch11 package. The program includes a swap method that is used by all the sorting methods to swap array elements. Describe an approach to modifying the program so that after calling a sorting method the program prints out the number of swaps needed by the sorting method. Implement your approach. Test your new program by...

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