1
- __author__ = "Omkar Pathak"
2
-
3
-
4
1
class Stack :
5
2
"""A stack is an abstract data type that serves as a collection of
6
3
elements with two principal operations: push() and pop(). push() adds an
@@ -11,14 +8,14 @@ class Stack:
11
8
https://en.wikipedia.org/wiki/Stack_(abstract_data_type)
12
9
"""
13
10
14
- def __init__ (self , limit = 10 ):
11
+ def __init__ (self , limit : int = 10 ):
15
12
self .stack = []
16
13
self .limit = limit
17
14
18
- def __bool__ (self ):
15
+ def __bool__ (self ) -> bool :
19
16
return bool (self .stack )
20
17
21
- def __str__ (self ):
18
+ def __str__ (self ) -> str :
22
19
return str (self .stack )
23
20
24
21
def push (self , data ):
@@ -29,21 +26,24 @@ def push(self, data):
29
26
30
27
def pop (self ):
31
28
""" Pop an element off of the top of the stack."""
32
- if self .stack :
33
- return self .stack .pop ()
34
- else :
29
+ if self .is_empty ():
35
30
raise IndexError ("pop from an empty stack" )
31
+ return self .stack .pop ()
36
32
37
33
def peek (self ):
38
34
""" Peek at the top-most element of the stack."""
39
- if self .stack :
40
- return self .stack [- 1 ]
35
+ if self .is_empty ():
36
+ raise IndexError ("peek from an empty stack" )
37
+ return self .stack [- 1 ]
41
38
42
- def is_empty (self ):
39
+ def is_empty (self ) -> bool :
43
40
""" Check if a stack is empty."""
44
41
return not bool (self .stack )
45
42
46
- def size (self ):
43
+ def is_full (self ) -> bool :
44
+ return self .size () == self .limit
45
+
46
+ def size (self ) -> int :
47
47
""" Return the size of the stack."""
48
48
return len (self .stack )
49
49
@@ -57,19 +57,22 @@ class StackOverflowError(BaseException):
57
57
58
58
59
59
if __name__ == "__main__" :
60
- stack = Stack ()
60
+ stack = Stack (10 )
61
61
for i in range (10 ):
62
62
stack .push (i )
63
63
64
- print ( "Stack demonstration: \n " )
65
- print ( "Initial stack: " + str (stack ) )
66
- print ( "pop(): " + str ( stack .pop ()))
67
- print ( "After pop(), the stack is now: " + str ( stack ))
68
- print ( "peek(): " + str ( stack . peek ()))
64
+ assert stack . is_full ( )
65
+ assert str ( stack ) == str ([ 0 , 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 ] )
66
+ assert stack .pop () == 9
67
+ assert stack . peek () == 8
68
+
69
69
stack .push (100 )
70
- print ("After push(100), the stack is now: " + str (stack ))
71
- print ("is_empty(): " + str (stack .is_empty ()))
72
- print ("size(): " + str (stack .size ()))
70
+ assert str (stack ) == str ([0 , 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 100 ])
71
+
72
+ assert not stack .is_empty ()
73
+ assert stack .size () == 10
74
+
73
75
num = 5
74
- if num in stack :
75
- print (f"{ num } is in stack" )
76
+ assert num in stack
77
+ num = 55
78
+ assert num not in stack
0 commit comments