Learn

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 1 is the maximum value in the entire list.
  • Every “child” element in the list must be smaller than their “parent”.

The first element we add to the list will automatically be the maximum value since there are no other elements in our heap. We’ll tackle the trickier aspects of maintaining these principles in the coming exercises

For now, lets define two class instance methods called .add() and .heapify_up():

  • .add() will handle adding an element to the heap via the .heap_list property.
  • .heapify_up() will do the work of maintaining the heap properties as we add additional elements.

Instructions

1.

Inside max_heap.py, define .add() within MaxHeap. .add() takes two arguments: self and element.

Give users a helpful print message like “Adding element to self.heap_list.”

2.

Inside of .add(), increment the internal element count, then add the element to the end of the internal list.

3.

Run the test code within script.py to see the element 42 added to the internal list.

4.

Define another method inside MaxHeap: .heapify_up(). It has self as a parameter.

Print out the message “Restoring the heap property…” within .heapify_up().

5.

Finish .add() by calling the .heapify_up() method we just defined.

Run the test code in script.py.

Sign up to start coding

By signing up for Codecademy, you agree to Codecademy's Terms of Service & Privacy Policy.
Already have an account?