Hi so I am trying to write a code that sorts an array from a given node such that it has a max heap property. The code is as follows:
def left_child(index):
return (index * 2) + 1
def right_child(index):
return (index + 1) * 2
def parent(index):
return (index - 1) // 2
def max_child_index(parent_index, array):
left = left_child(parent_index)
right = right_child(parent_index)
if left < len(array) and array[left] >= array[right]:
return left
elif left < len(array) and array[left] < array[right]:
return right
def max_heapify(array, index):
swapped = True
while swapped == True:
swapped = False
max_child_index = max_child_index(index, array)
if array[index] < array[max_child_index]:
array[index], array[max_child_index] = array[max_child_index], array[index]
print(array)
index = max_child_index
swapped = True
So I then tested the code with the following:
array = [1, 14, 9, 10, 2, 8, 3, 7, 4, 16]
max_heapify(array, 0)
assert array == [14, 10, 9, 7, 2, 8, 3, 1, 4, 16]
but then the following error was shown:
UnboundLocalError Traceback (most recent call last)
<ipython-input-17-ba04a5f4816a> in <module>
1 array = [1, 14, 9, 10, 2, 8, 3, 7, 4, 16]
----> 2 max_heapify(array, 0)
3 print(array)
<ipython-input-16-ebac3db736fd> in max_heapify(array, index)
3 while swapped == True:
4 swapped = False
----> 5 max_child_index = max_child_index(index, array)
6 if array[index] < array[max_child_index]:
7 array[index], array[max_child_index] = array[max_child_index], array[index]
UnboundLocalError: local variable 'max_child_index' referenced before assignment
What I do not get is at the line in max_heapify where Python says the error occurs, that line is the first time when the local variable max_child_index is mentioned, declared and assigned a value. So, why does Python think that I have already used it?
Your function and variable have the same name, which causes an error.
max_child_index = max_child_index(...)You should change one of them.