@@ -33,7 +33,23 @@ def __str__(self) -> str:
3333 return str (self .stack )
3434
3535 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+ """
3753 if len (self .stack ) >= self .limit :
3854 raise StackOverflowError
3955 self .stack .append (data )
@@ -42,6 +58,12 @@ def pop(self) -> T:
4258 """
4359 Pop an element off of the top of the stack.
4460
61+ >>> S = Stack()
62+ >>> S.push(-5)
63+ >>> S.push(10)
64+ >>> S.pop()
65+ 10
66+
4567 >>> Stack().pop()
4668 Traceback (most recent call last):
4769 ...
@@ -55,7 +77,13 @@ def peek(self) -> T:
5577 """
5678 Peek at the top-most element of the stack.
5779
58- >>> Stack().pop()
80+ >>> S = Stack()
81+ >>> S.push(-5)
82+ >>> S.push(10)
83+ >>> S.peek()
84+ 10
85+
86+ >>> Stack().peek()
5987 Traceback (most recent call last):
6088 ...
6189 data_structures.stacks.stack.StackUnderflowError
@@ -65,18 +93,68 @@ def peek(self) -> T:
6593 return self .stack [- 1 ]
6694
6795 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+ """
69108 return not bool (self .stack )
70109
71110 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+ """
72121 return self .size () == self .limit
73122
74123 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+ """
76142 return len (self .stack )
77143
78144 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+ """
80158 return item in self .stack
81159
82160
@@ -131,3 +209,7 @@ def test_stack() -> None:
131209
132210if __name__ == "__main__" :
133211 test_stack ()
212+
213+ import doctest
214+
215+ doctest .testmod ()
0 commit comments