Skip to content

Commit 66f9adc

Browse files
committed
Fix up Heap class
1 parent c2dbf17 commit 66f9adc

File tree

1 file changed

+32
-13
lines changed

1 file changed

+32
-13
lines changed

heaps.py

Lines changed: 32 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -1,33 +1,52 @@
11
import heapq
2+
from functools import partial
23

34

45
class Heap:
56
"""Simple wrapper around heapq functions.
67
7-
Why the standard library doesn't include a class like this is beyond me...
8+
>>> h = Heap()
9+
>>> h.push((5, 'write code'))
10+
>>> h.push((7, 'release product'))
11+
>>> h.push((1, 'write spec'))
12+
>>> h.push((3, 'create tests'))
13+
>>> h.pop()
14+
(1, 'write spec')
15+
16+
Look ma, heapsort!
17+
18+
>>> list(Heap([1, 3, 5, 7, 9, 2, 4, 6, 8, 0]))
19+
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
20+
821
"""
922

1023
def __init__(self, items=None):
1124
if items is None:
1225
self._items = []
1326
else:
14-
heapq.heapify(items)
15-
self._items = items
27+
self._items = list(items)
28+
heapq.heapify(self._items)
29+
for name in ['push', 'pop', 'pushpop', 'replace']:
30+
func = getattr(heapq, 'heap' + name)
31+
setattr(self, name, partial(func, self._items))
1632

17-
def push(self, item):
18-
return heapq.heappush(self._items, item)
33+
def peek(self):
34+
return self._items[0]
1935

20-
def pop(self):
21-
return heapq.heappop(self._items)
36+
def __bool__(self):
37+
return bool(self._items)
2238

23-
def pushpop(self, item):
24-
return heapq.pushpop(self._items)
39+
def __len__(self):
40+
return len(self._items)
2541

26-
def replace(self, item):
27-
return heapq.heapreplace(self._items, item)
42+
def __next__(self):
43+
try:
44+
return self.pop()
45+
except IndexError:
46+
raise StopIteration
2847

29-
def peek(self):
30-
return self._items[0]
48+
def __iter__(self):
49+
return self
3150

3251

3352
class PriorityQueue:

0 commit comments

Comments
 (0)