@@ -33,7 +33,23 @@ def __str__(self) -> str:
33
33
return str (self .stack )
34
34
35
35
def push (self , data : T ) -> None :
36
- """Push an element to the top of the stack."""
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
+ """
37
53
if len (self .stack ) >= self .limit :
38
54
raise StackOverflowError
39
55
self .stack .append (data )
@@ -42,6 +58,12 @@ def pop(self) -> T:
42
58
"""
43
59
Pop an element off of the top of the stack.
44
60
61
+ >>> S = Stack()
62
+ >>> S.push(-5)
63
+ >>> S.push(10)
64
+ >>> S.pop()
65
+ 10
66
+
45
67
>>> Stack().pop()
46
68
Traceback (most recent call last):
47
69
...
@@ -55,7 +77,13 @@ def peek(self) -> T:
55
77
"""
56
78
Peek at the top-most element of the stack.
57
79
58
- >>> Stack().pop()
80
+ >>> S = Stack()
81
+ >>> S.push(-5)
82
+ >>> S.push(10)
83
+ >>> S.peek()
84
+ 10
85
+
86
+ >>> Stack().peek()
59
87
Traceback (most recent call last):
60
88
...
61
89
data_structures.stacks.stack.StackUnderflowError
@@ -65,18 +93,68 @@ def peek(self) -> T:
65
93
return self .stack [- 1 ]
66
94
67
95
def is_empty (self ) -> bool :
68
- """Check if a stack is empty."""
96
+ """
97
+ Check if a stack is empty.
98
+
99
+ >>> S = Stack()
100
+ >>> S.is_empty()
101
+ True
102
+
103
+ >>> S = Stack()
104
+ >>> S.push(10)
105
+ >>> S.is_empty()
106
+ False
107
+ """
69
108
return not bool (self .stack )
70
109
71
110
def is_full (self ) -> bool :
111
+ """
112
+ >>> S = Stack()
113
+ >>> S.is_full()
114
+ False
115
+
116
+ >>> S = Stack(1)
117
+ >>> S.push(10)
118
+ >>> S.is_full()
119
+ True
120
+ """
72
121
return self .size () == self .limit
73
122
74
123
def size (self ) -> int :
75
- """Return the size of the stack."""
124
+ """
125
+ Return the size of the stack.
126
+
127
+ >>> S = Stack(3)
128
+ >>> S.size()
129
+ 0
130
+
131
+ >>> S = Stack(3)
132
+ >>> S.push(10)
133
+ >>> S.size()
134
+ 1
135
+
136
+ >>> S = Stack(3)
137
+ >>> S.push(10)
138
+ >>> S.push(20)
139
+ >>> S.size()
140
+ 2
141
+ """
76
142
return len (self .stack )
77
143
78
144
def __contains__ (self , item : T ) -> bool :
79
- """Check if item is in stack"""
145
+ """
146
+ Check if item is in stack
147
+
148
+ >>> S = Stack(3)
149
+ >>> S.push(10)
150
+ >>> 10 in S
151
+ True
152
+
153
+ >>> S = Stack(3)
154
+ >>> S.push(10)
155
+ >>> 20 in S
156
+ False
157
+ """
80
158
return item in self .stack
81
159
82
160
@@ -131,3 +209,7 @@ def test_stack() -> None:
131
209
132
210
if __name__ == "__main__" :
133
211
test_stack ()
212
+
213
+ import doctest
214
+
215
+ doctest .testmod ()
0 commit comments