Why doesn't my heapify work?
Diez B. Roggisch
deets at nospam.web.de
Wed Feb 7 13:06:14 EST 2007
Dongsheng Ruan wrote:
> I want to turn an Array into a heap, but my code just doesn't work: no
> change after execution.
>
> A=[3,5,4,9,6,7]
> m=len(A)-1
>
>
>
> for i in range(m,1):
> t=(i-1)/2
> if A[i]>A[t]:
> A[i],A[t]=A[t],A[i]
First of all, there is the module heapq that will just do it.
And then you seem to misunderstand how the range-function works. range(m, 1)
will always be the empty list. See
pydoc range
for how it operates.
Overall, your code is very unpythonic, to say the least. I suggest you start
reading the python tutorial first:
http://docs.python.org/tut/
Especially the looping techniques section:
http://docs.python.org/tut/node7.html#SECTION007600000000000000000
Diez
More information about the Python-list
mailing list