I have two questions:
1) Recently I’m try to build a max heap. Even though I read CLRS I can’t find the bug as I run it. The following is my code…
def maxHeapify(list, index):
int = index
left = (int+1) * 2 - 1
right = (int+1) * 2
largest = 0
if left < len(list):
if (left <= len(list)) & (list[left] >= list[int]):
largest = left
else:
largest = int
if right < len(list):
if (right <= len(list)) & (list[right] >= list[largest]):
largest = right
else:
pass
if largest != int:
listNew = swapWithinList(list, int, largest)
listNew = maxHeapify(listNew, largest)
else:
return listNew
def swapWithinList(list, id1, id2):
num1 = list[id1]
num2 = list[id2]
listNew = list[:id1]
listNew.append(num2)
listNew = listNew + list[(id1+1):id2]
listNew.append(num1)
listNew = listNew + list[(id2+1):]
return listNew
I give input but the console just says:
UnboundLocalError: local variable 'listNew' referenced before assignment
does it mean that I put the return statement on the wrong line or there’s something I haven’t mentioned?
2) What is a iteration?
I am a bit embarrassed when I ask the question. But what is a iteration? Wiki says each repetition of the process means it, so is it a result the loop gives each round?
And iterator seems a basic element in Python, what’s difference between iterator and iteration?
1:
Without further comments, here’s the code adapted from Wikipedia:
Example:
Result:
Let us know if you have any questions.
2:
Iteration in python is technically a process of repeatedly calling some object’s
next()method until it raises theStopIterationexception. Object that possesses thisnextmethod is called Iterator. An object that is able to provide an Iterator for the calling code is called Iterable.