0

I'm trying to animate a max heap tree step by step, however, I am struggling to store the intermediate steps in between in a list. When I run my code, it overlaps each of the values in the list with the final answer.

nums = [4, 1, 3, 2, 16, 9, 10, 14, 8, 7]

def max_heapify(nums, index=0):
    left = 2*index + 1
    right = 2*index + 2

    if left <= len(nums) - 1 and nums[left] > nums[index]:
        largest = left
    else:
        largest = index

    if right < len(nums) - 1 and nums[right] > nums[largest]:
        largest = right

    if largest != index:
        nums[index], nums[largest] = nums[largest], nums[index]
        max_heapify(nums, largest)

def build_max_heap(nums):
    frame_list = []
    for i in range(((len(nums)//2) - 1), -1, -1):
        frame_list.append(nums)
        max_heapify(nums, i)
    return (frame_list)

build_max_heap(nums)

Returns:

[[16, 14, 10, 8, 7, 9, 3, 2, 4, 1],
 [16, 14, 10, 8, 7, 9, 3, 2, 4, 1],
 [16, 14, 10, 8, 7, 9, 3, 2, 4, 1],
 [16, 14, 10, 8, 7, 9, 3, 2, 4, 1],
 [16, 14, 10, 8, 7, 9, 3, 2, 4, 1]]
martineau
  • 119,623
  • 25
  • 170
  • 301
  • This link is in the context of assignment, but the same principles apply when you append one list to another. Add `print(frame_list)` inside your for loop to see how it changes on each iteration. – Code-Apprentice Mar 10 '22 at 23:33
  • To avoid the problem, append a *copy* of the current list to the `frame_list` — i.e. `frame_list.append(nums.copy())`. You'll also need to do it one additional time immediately before the `return frame_list` (or change the `for` loop to `for i in range(((len(nums)//2)), -1, -1):`). – martineau Mar 10 '22 at 23:44

0 Answers0