MCPcopy
hub / github.com/TheAlgorithms/Python / Stack

Class Stack

data_structures/stacks/stack.py:16–158  ·  view source on GitHub ↗

A stack is an abstract data type that serves as a collection of elements with two principal operations: push() and pop(). push() adds an element to the top of the stack, and pop() removes an element from the top of a stack. The order in which elements come off of a stack are Last In,

Source from the content-addressed store, hash-verified

14
15
16class Stack[T]:
17 """A stack is an abstract data type that serves as a collection of
18 elements with two principal operations: push() and pop(). push() adds an
19 element to the top of the stack, and pop() removes an element from the top
20 of a stack. The order in which elements come off of a stack are
21 Last In, First Out (LIFO).
22 https://en.wikipedia.org/wiki/Stack_(abstract_data_type)
23 """
24
25 def __init__(self, limit: int = 10):
26 self.stack: list[T] = []
27 self.limit = limit
28
29 def __bool__(self) -> bool:
30 return bool(self.stack)
31
32 def __str__(self) -> str:
33 return str(self.stack)
34
35 def push(self, data: T) -> None:
36 """
37 Push an element to the top of the stack.
38
39 >>> S = Stack(2) # stack size = 2
40 >>> S.push(10)
41 >>> S.push(20)
42 >>> print(S)
43 [10, 20]
44
45 >>> S = Stack(1) # stack size = 1
46 >>> S.push(10)
47 >>> S.push(20)
48 Traceback (most recent call last):
49 ...
50 data_structures.stacks.stack.StackOverflowError
51
52 """
53 if len(self.stack) >= self.limit:
54 raise StackOverflowError
55 self.stack.append(data)
56
57 def pop(self) -> T:
58 """
59 Pop an element off of the top of the stack.
60
61 >>> S = Stack()
62 >>> S.push(-5)
63 >>> S.push(10)
64 >>> S.pop()
65 10
66
67 >>> Stack().pop()
68 Traceback (most recent call last):
69 ...
70 data_structures.stacks.stack.StackUnderflowError
71 """
72 if not self.stack:
73 raise StackUnderflowError

Callers 4

infix_to_postfixFunction · 0.70
test_stackFunction · 0.70
balanced_parenthesesFunction · 0.70

Calls

no outgoing calls

Tested by 1

test_stackFunction · 0.56