Question

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 foll

0 0
Add a comment Improve this question Transcribed image text
Answer #1
class BinaryHeap:
    def __init__(self):
        self.items = []
 
    def size(self):
        return len(self.items)
 
    def parent(self, i):
        return (i - 1)//2
 
    def left(self, i):
        return 2*i + 1
 
    def right(self, i):
        return 2*i + 2
 
    def get(self, i):
        return self.items[i]
 
    def get_max(self):
        if self.size() == 0:
            return None
        return self.items[0]
 
    def extract_max(self):
        if self.size() == 0:
            return None
        largest = self.get_max()
        self.items[0] = self.items[-1]
        del self.items[-1]
        self.max_heapify(0)
        return largest
 
    def max_heapify(self, i):
        l = self.left(i)
        r = self.right(i)
        if (l <= self.size() - 1 and self.get(l) > self.get(i)):
            largest = l
        else:
            largest = i
        if (r <= self.size() - 1 and self.get(r) > self.get(largest)):
            largest = r
        if (largest != i):
            self.swap(largest, i)
            self.max_heapify(largest)
 
    def swap(self, i, j):
        self.items[i], self.items[j] = self.items[j], self.items[i]
 
    def insert(self, key):
        index = self.size()
        self.items.append(key)
 
        while (index != 0):
            p = self.parent(index)
            if self.get(p) < self.get(index):
                self.swap(p, index)
            index = p
 
 
bheap = BinaryHeap()
 
print('Menu')
print('insert <data>')
print('max get')
print('max extract')
print('quit')
 
while True:
    do = input('What would you like to do? ').split()
 
    operation = do[0].strip().lower()
    if operation == 'insert':
        data = int(do[1])
        bheap.insert(data)
    elif operation == 'max':
        suboperation = do[1].strip().lower()
        if suboperation == 'get':
            print('Maximum value: {}'.format(bheap.get_max()))
        elif suboperation == 'extract':
            print('Maximum value removed: {}'.format(bheap.extract_max()))
 
    elif operation == 'quit':
        break
Add a comment
Know the answer?
Add Answer to:
Min heap class implementation in Python. Implement a min-using an array. Your min-heap class will have...
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 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...

  • in python 11.1 Binary Search Tree In this assignment, you will implement a Binary Search Tree...

    in python 11.1 Binary Search Tree In this assignment, you will implement a Binary Search Tree You will also need to implement a Node class. This class will not be tested, but is needed to implement the BST. Your BST must implement the following methods. You are free to implement additional helper methods. It is recommended you create your own helper methods Constructor: Creates an Empty Tree String Method: Returns the string "Empty Tree" for an empty tree. Otherwise, returns...

  • In class, we discussed the priority queue (PQ) ADT implemented using min-heap. In a min-heap, the...

    In class, we discussed the priority queue (PQ) ADT implemented using min-heap. In a min-heap, the element of the heap with the smallest key is the root of the binary tree. On the other hand, a max-heap has as root the element with the biggest key, and the relationship between the keys of a node and its parent is reversed of that of a min-heap. We also discussed an array-based implementation of heaps. In this assignment, your task is to...

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

  • 1. Which of the following is a proper array representation a binary min heap?

    1. Which of the following is a proper array representation a binary min heap?2. A heap is implemented using an array. At what index will the right child of node at index i be found? Note, the Oth position of the array is not used.Select one:a. i/2b. 2 i+1c. i-1d. 2 i3. Consider the following array of length 6. Elements from the array are added, in the given order, to a max heap. The heap is initially empty and stored as an array.A={18,5,37,44,27,53}What...

  • Please I need help ASAP Java Programing: Binary Search Tree Fully implement the BST class in Listing 25.4 (on page 961 of the 11th Edition of the text). Design and write a (main) driver program to com...

    Please I need help ASAP Java Programing: Binary Search Tree Fully implement the BST class in Listing 25.4 (on page 961 of the 11th Edition of the text). Design and write a (main) driver program to completely test every method in the BST class to ensure the class meets all its requirements. You should read the Listing 25.5: TestBST.java for an idea of what your program should look like. Listing 25.4 BST.java public class BST> extends AbstractTree { protected TreeNode...

  • 5. A three-heap with n elements can be stored in an array A, where A[O] contains...

    5. A three-heap with n elements can be stored in an array A, where A[O] contains the root of the tree. a) Draw the three-heap that results from inserting 5, 2, 8, 3, 6, 4, 9, 7, 1 in that order into an initially empty three-heap. You do not need to show the array representation of the heap. You are only required to show the final tree, although if you draw intermediate trees. b) Assuming that elements are placed in...

  • Using the following implementation of Tree class Node   {   public int iData;              // data item (key)   public...

    Using the following implementation of Tree class Node   {   public int iData;              // data item (key)   public double dData;           // data item   public Node leftChild;         // this node's left child   public Node rightChild;        // this node's right child   public void displayNode()      // display ourself      {      System.out.print('{');      System.out.print(iData);      System.out.print(", ");      System.out.print(dData);      System.out.print("} ");      }   }  // end class Node //------------------------------------------------------------------ import java.io.IOException; import java.util.Stack; public class Tree { private Node root; // first node of tree // ------------------------------------------------------------- public Tree() // constructor { root = null; }...

  • Must be in JAVA 1. Design and implement a Binary Heap class that must support "insert"...

    Must be in JAVA 1. Design and implement a Binary Heap class that must support "insert" and "deleteMin" operations 2. Design and implement a driver (the main method) that does the following: (a) Creates an array that contains a list of 4099 integers, in a random order, between 0 to to 4098. (b) insert, into the first binary heap that is initially empty, the numbers in the array sequentially from the start to the end (c) Initialize the second empty...

  • In Java. How would this method look? LinkedBinaryTree.java import java.util.Iterator; public class LinkedBinaryTree implements BinaryTreeADT {...

    In Java. How would this method look? LinkedBinaryTree.java import java.util.Iterator; public class LinkedBinaryTree implements BinaryTreeADT {    private BinaryTreeNode root;    /**    * Creates an empty binary tree.    */    public LinkedBinaryTree() {        root = null;    }    /**    * Creates a binary tree from an existing root.    */    public LinkedBinaryTree(BinaryTreeNode root) {        this.root = root;    }    /**    * Creates a binary tree with the specified element...

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