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

Class ArrayStack

algorithms/data_structures/stack.py:58–126  ·  view source on GitHub ↗

Stack implemented with a dynamic array. Examples: >>> s = ArrayStack() >>> s.push(1) >>> s.pop() 1

Source from the content-addressed store, hash-verified

56
57
58class ArrayStack(AbstractStack):
59 """Stack implemented with a dynamic array.
60
61 Examples:
62 >>> s = ArrayStack()
63 >>> s.push(1)
64 >>> s.pop()
65 1
66 """
67
68 def __init__(self, size: int = 10) -> None:
69 """Initialize with a fixed-size array.
70
71 Args:
72 size: Initial capacity of the underlying array.
73 """
74 super().__init__()
75 self._array: list[object | None] = [None] * size
76
77 def __iter__(self) -> Iterator[object]:
78 probe = self._top
79 while True:
80 if probe == -1:
81 return
82 yield self._array[probe]
83 probe -= 1
84
85 def push(self, value: object) -> None:
86 """Push a value onto the stack.
87
88 Args:
89 value: The value to push.
90 """
91 self._top += 1
92 if self._top == len(self._array):
93 self._expand()
94 self._array[self._top] = value
95
96 def pop(self) -> object:
97 """Remove and return the top element.
98
99 Returns:
100 The top element.
101
102 Raises:
103 IndexError: If the stack is empty.
104 """
105 if self.is_empty():
106 raise IndexError("Stack is empty")
107 value = self._array[self._top]
108 self._top -= 1
109 return value
110
111 def peek(self) -> object:
112 """Return the top element without removing it.
113
114 Returns:
115 The top element.

Callers 1

test_array_stackMethod · 0.90

Calls

no outgoing calls

Tested by 1

test_array_stackMethod · 0.72