Key Concepts

Review core concepts you need to learn to master this subject

.add() Method

def add(self, element): self.count += 1 print("Adding: {0} to {1}".format(element, self.heap_list)) self.heap_list.append(element) self.heapify_up()

The .add() method is used in the MaxHeap class to add new values to a max-heap while maintaining the max-heap property that a parent must have a larger value than its children.

Max-Heaps: Python
Lesson 1 of 2
  1. 1
    We’re going to implement a max-heap in Python. Max-heaps efficiently keep track of the maximum value in a dataset, even as we add and remove elements. Max-heaps are nearly identical to a min-…
  2. 2
    Our MaxHeap class will store two pieces of information in the form of instance attributes: * A Python list of the elements within the heap. * A count of the elements within the heap. To make our …
  3. 3
    Our MaxHeap class isn’t very useful if all it ever contains is None. Let’s build the functionality to add elements to our max-heap. Our MaxHeap must abide by two principles: * The element at index…
  4. 4
    Great work so far! Our MaxHeap adds elements to heap_list, keeps count of the number elements inside the heap, and has the beginnings of .heapify_up(). Before we dive into the logic for .heapify_u…
  5. 5
    Now that we understand how to determine the relationship of elements with the internal list, we’re ready to finish .heapify_up(). We need to make sure that every child is smaller in value than th…
  6. 6
    Nice work! You’ve implemented a MaxHeap class in Python. Heaps are useful because they’re efficient in maintaining their heap properties. Let’s recap what we learned: * A max-heap tracks the m…

How you'll master it

Stress-test your knowledge with quizzes that help commit syntax to memory

Pro Logo