|
1 | 1 | import heapq |
| 2 | +from functools import partial |
2 | 3 |
|
3 | 4 |
|
4 | 5 | class Heap: |
5 | 6 | """Simple wrapper around heapq functions. |
6 | 7 |
|
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 | +
|
8 | 21 | """ |
9 | 22 |
|
10 | 23 | def __init__(self, items=None): |
11 | 24 | if items is None: |
12 | 25 | self._items = [] |
13 | 26 | 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)) |
16 | 32 |
|
17 | | - def push(self, item): |
18 | | - return heapq.heappush(self._items, item) |
| 33 | + def peek(self): |
| 34 | + return self._items[0] |
19 | 35 |
|
20 | | - def pop(self): |
21 | | - return heapq.heappop(self._items) |
| 36 | + def __bool__(self): |
| 37 | + return bool(self._items) |
22 | 38 |
|
23 | | - def pushpop(self, item): |
24 | | - return heapq.pushpop(self._items) |
| 39 | + def __len__(self): |
| 40 | + return len(self._items) |
25 | 41 |
|
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 |
28 | 47 |
|
29 | | - def peek(self): |
30 | | - return self._items[0] |
| 48 | + def __iter__(self): |
| 49 | + return self |
31 | 50 |
|
32 | 51 |
|
33 | 52 | class PriorityQueue: |
|
0 commit comments