heap doesn't appear to work as described

7stud bbxx789_05ss at yahoo.com
Wed Apr 4 13:01:11 EDT 2007


On Apr 4, 7:05 am, s... at pobox.com wrote:
>     >>>> My book says that in a heap, a value at position i will be than the
>     >>>> values at positions 2*i and 2*i + 1.
>
>     >> I am sure your book either uses 1-based arrays or a 0-based arrays
>     >> with the first not used.  The need to keep these alternatives in mind
>     >> is an unfortunate fact of programming life.
>
>     > My book uses lists.
>
> Yes, but is the first element of the list addressed as element 1 or element
> 0?

Here is the example:
---------
from heapq import *
from random import shuffle

data = range(10)
shuffle(data)
heap = []
for n in data:
    heappush(heap, n)
print heap
heappush(heap, 0.5)
print heap

#my test:
print heap[0]  #output: 0
-------

It's from Beginning Python: Novice to Professional, which I think is a
really poorly written book chock full of mistakes and ambiguous
example code.







More information about the Python-list mailing list