Skip to content

Commit faa27b3

Browse files
committed
feat: finish stack using heap (gotta use ALL the built in libs)
1 parent cca312e commit faa27b3

File tree

1 file changed

+57
-0
lines changed

1 file changed

+57
-0
lines changed

heap_stack/stack.py

Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
1+
import heapq
2+
from dataclasses import dataclass
3+
4+
5+
@dataclass
6+
class Item:
7+
key: int
8+
value: int
9+
10+
def __lt__(self, other: "Item"):
11+
return self.key < other.key
12+
13+
14+
class Heap:
15+
def __init__(self) -> None:
16+
self.__data: list[Item] = []
17+
18+
def push(self, item: Item) -> None:
19+
heapq.heappush(self.__data, item)
20+
21+
def pop(self) -> Item:
22+
return heapq.heappop(self.__data)
23+
24+
def __repr__(self) -> str:
25+
return str(self.__data)
26+
27+
28+
class Stack:
29+
def __init__(self) -> None:
30+
self.heap = Heap()
31+
self.current_key = 0
32+
33+
def push(self, item: int) -> None:
34+
# the heapq module supports max heaps buts it a lil sus and undocumented
35+
# so instead of using that im just negating the key
36+
# this will make the most recent item at the top of the heap
37+
self.heap.push(Item(self.current_key * -1, item))
38+
self.current_key += 1
39+
40+
def pop(self) -> int:
41+
item = self.heap.pop()
42+
return item.value
43+
44+
45+
s = Stack()
46+
47+
s.push(5)
48+
s.push(7)
49+
s.push(10)
50+
s.push(2)
51+
s.push(12)
52+
53+
assert s.pop() == 12
54+
assert s.pop() == 2
55+
assert s.pop() == 10
56+
assert s.pop() == 7
57+
assert s.pop() == 5

0 commit comments

Comments
 (0)