Question: please can you complete this python code but do not chance any works from code. and send me the code which i can copy and

please can you complete this python code but do not chance any works from code. and send me the code which i can copy and paste. Thank you so much.

In this exercise, you will write a function to rearrange an array to be a max heap. As was mentioned in the lecture, a max heap is a heap where every node is greater than its children.I've given you three functions to navigate your heap: get_parent(), get_left_child(), and get_right_child(). When passed an index in the array, these return the index in the array that holds the node with the respective relationship.I have also implemented sift_up for you from the in class work, you will use it to make the heapAdditionally, I've given you the function is_max_heap(). When passed an array, it will return True if it is a max heap, and False otherwise. This should be used for testing and not in your heapify() function.

What you need to do

  1. Loop through all indexes of the array from left to right

  2. Call sift_up on that index

  3. Expected behavior:

     
     

    arr = [1,2,3,4,5]

    heapify(arr)

    print(is_max_heap(arr))
  4. def get_parent(node_idx): """Return the index of the parent of a node.""" return (node_idx-1) // 2

  5. def get_left_child(node_idx): """Return the index of the left child of a node.""" return node_idx * 2 + 1

    def get_right_child(node_idx): """Return the index of the right child of a node.""" return node_idx * 2 + 2 def sift_up(heap, node_idx): if node_idx == 0: return

    """ get the root node index """ root_idx = get_parent(node_idx) if heap[node_idx] > heap[root_idx]: """ If this node value is greater than the root we need to swap and continue sifting """ heap[node_idx], heap[root_idx] = heap[root_idx], heap[node_idx] return sift_up(heap, root_idx)

    def is_max_heap(heap): """Return true if the array is a max heap.""" size = len(heap) left = all(heap[i] > heap[get_left_child(i)] for i in range(size) if get_left_child(i) < size) right = all(heap[i] > heap[get_right_child(i)] for i in range(size) if get_right_child(i) < size) return left and right

    def heapify(arr): """Modify an array to be a max heap.""" # Your code here

    arr = [1,2,3,4,5] heapify(arr) print(is_max_heap(arr))

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Databases Questions!