MCPcopy Create free account
hub / github.com/ActiveState/code / Heap

Class Heap

recipes/Python/437116_Wrapper_class_heapq/recipe-437116.py:3–57  ·  view source on GitHub ↗

This is a wrapper class for the heap functions provided by the heapq module.

Source from the content-addressed store, hash-verified

1import heapq
2
3class Heap(list):
4 """This is a wrapper class for the heap functions provided
5 by the heapq module.
6 """
7 __slots__ = ()
8
9 def __init__(self, t=[]):
10 self.extend(t)
11 self.heapify()
12
13 push = heapq.heappush
14 popmin = heapq.heappop
15 replace = heapq.heapreplace
16 heapify = heapq.heapify
17
18 def pushpop(self, item):
19 "Push the item onto the heap and then pop the smallest value"
20 if self and self[0] < item:
21 return heapq.heapreplace(self, item)
22 return item
23
24 def __iter__(self):
25 "Return a destructive iterator over the heap's elements"
26 try:
27 while True:
28 yield self.popmin()
29 except IndexError:
30 pass
31
32 def reduce(self, pos, newitem):
33 "Replace self[pos] with a lower value item and then reheapify"
34 while pos > 0:
35 parentpos = (pos - 1) >> 1
36 parent = self[parentpos]
37 if parent <= newitem:
38 break
39 self[pos] = parent
40 pos = parentpos
41 self[pos] = newitem
42
43 def is_heap(self):
44 "Return True if the heap has the heap property; False otherwise"
45 n = len(self)
46 # The largest index there's any point to looking at
47 # is the largest with a child index in-range, so must have 2*i + 1 < n,
48 # or i < (n-1)/2. If n is even = 2*j, this is (2*j-1)/2 = j-1/2 so
49 # j-1 is the largest, which is n//2 - 1. If n is odd = 2*j+1, this is
50 # (2*j+1-1)/2 = j so j-1 is the largest, and that's again n//2-1.
51 try:
52 for i in xrange(n//2):
53 if self[i] > self[2*i+1]: return False
54 if self[i] > self[2*i+2]: return False
55 except IndexError:
56 pass
57 return True
58
59
60def heapsort(seq):

Callers 2

heapsortFunction · 0.70
recipe-437116.pyFile · 0.70

Calls

no outgoing calls

Tested by

no test coverage detected