1 """Unittests for heapq."""
3 from test
.test_support
import verify
, vereq
, verbose
, TestFailed
5 from heapq
import heappush
, heappop
, heapify
, heapreplace
8 def check_invariant(heap
):
9 # Check the heap invariant.
10 for pos
, item
in enumerate(heap
):
11 if pos
: # pos 0 has no parent
12 parentpos
= (pos
-1) >> 1
13 verify(heap
[parentpos
] <= item
)
15 # An iterator returning a heap's elements, smallest-first.
16 class heapiter(object):
17 def __init__(self
, heap
):
22 return heappop(self
.heap
)
30 # 1) Push 100 random numbers and pop them off, verifying all's OK.
35 item
= random
.random()
46 vereq(data_sorted
, results
)
47 # 2) Check that the invariant holds for a sorted array
48 check_invariant(results
)
49 # 3) Naive "N-best" algorithm
56 vereq(heap
, data_sorted
[-10:])
58 for size
in range(30):
59 heap
= [random
.random() for dummy
in range(size
)]
62 # 5) Less-naive "N-best" algorithm, much faster (if len(data) is big
63 # enough <wink>) than sorting all of data. However, if we had a max
64 # heap instead of a min heap, it could go faster still via
65 # heapify'ing all of data (linear time), then doing 10 heappops
66 # (10 log-time steps).
69 for item
in data
[10:]:
70 if item
> heap
[0]: # this gets rarer the longer we run
71 heapreplace(heap
, item
)
72 vereq(list(heapiter(heap
)), data_sorted
[-10:])
73 # 6) Exercise everything with repeated heapsort checks
74 for trial
in xrange(100):
75 size
= random
.randrange(50)
76 data
= [random
.randrange(25) for i
in range(size
)]
77 if trial
& 1: # Half of the time, use heapify
80 else: # The rest of the time, use heappush
85 sorted = [heappop(heap
) for i
in range(size
)]
91 if __name__
== "__main__":