MCPcopy
hub / github.com/keon/algorithms / OrderedStack

Class OrderedStack

algorithms/stack/ordered_stack.py:18–93  ·  view source on GitHub ↗

A stack that keeps elements in ascending order (bottom to top). Examples: >>> s = OrderedStack() >>> s.push(3) >>> s.push(1) >>> s.push(2) >>> s.pop() 3

Source from the content-addressed store, hash-verified

16
17
18class OrderedStack:
19 """A stack that keeps elements in ascending order (bottom to top).
20
21 Examples:
22 >>> s = OrderedStack()
23 >>> s.push(3)
24 >>> s.push(1)
25 >>> s.push(2)
26 >>> s.pop()
27 3
28 """
29
30 def __init__(self) -> None:
31 """Initialize an empty ordered stack."""
32 self.items: list[int] = []
33
34 def is_empty(self) -> bool:
35 """Check if the stack is empty.
36
37 Returns:
38 True if the stack has no elements.
39 """
40 return self.items == []
41
42 def _push_direct(self, item: int) -> None:
43 """Append an item without enforcing order.
44
45 Args:
46 item: The value to append.
47 """
48 self.items.append(item)
49
50 def push(self, item: int) -> None:
51 """Push an item while maintaining sorted order.
52
53 Args:
54 item: The value to push.
55 """
56 temp_stack = OrderedStack()
57 if self.is_empty() or item > self.peek():
58 self._push_direct(item)
59 else:
60 while item < self.peek() and not self.is_empty():
61 temp_stack._push_direct(self.pop())
62 self._push_direct(item)
63 while not temp_stack.is_empty():
64 self._push_direct(temp_stack.pop())
65
66 def pop(self) -> int:
67 """Remove and return the top element.
68
69 Returns:
70 The top (largest) element.
71
72 Raises:
73 IndexError: If the stack is empty.
74 """
75 if self.is_empty():

Callers 2

test_ordered_stackMethod · 0.90
pushMethod · 0.85

Calls

no outgoing calls

Tested by 1

test_ordered_stackMethod · 0.72