File tree Expand file tree Collapse file tree 1 file changed +50
-0
lines changed Expand file tree Collapse file tree 1 file changed +50
-0
lines changed Original file line number Diff line number Diff line change
1
+ class Stack :
2
+ class EmptyStackError (Exception ):
3
+ def __str__ (self ) -> str :
4
+ return "Stack is empty."
5
+
6
+ def __init__ (self ) -> None :
7
+ self ._data : list [object ] = []
8
+ self ._size : int = 0
9
+
10
+ def __len__ (self ) -> int :
11
+ return self ._size
12
+
13
+ def length (self ) -> int :
14
+ return self .__len__ ()
15
+
16
+ def __str__ (self ) -> str :
17
+ return str (self ._data )
18
+
19
+ def is_empty (self ) -> bool :
20
+ return self ._size == 0
21
+
22
+ def top (self ) -> object :
23
+ if self .is_empty ():
24
+ raise Stack .EmptyStackError
25
+ return self ._data [- 1 ]
26
+
27
+ def push (self , element : object ) -> None :
28
+ self ._data .append (element )
29
+ self ._size += 1
30
+
31
+ def pop (self ) -> object :
32
+ if self .is_empty ():
33
+ raise Stack .EmptyStackError
34
+ self ._size -= 1
35
+ return self ._data .pop ()
36
+
37
+
38
+ if __name__ == '__main__' :
39
+ stack = Stack ()
40
+ print (stack .is_empty ())
41
+ for i in range (10 ):
42
+ stack .push (i )
43
+ print (stack .top ())
44
+ print (stack )
45
+ print (len (stack ))
46
+ print (stack .length ())
47
+ print (stack .is_empty ())
48
+ for i in range (10 ):
49
+ print (stack .pop ())
50
+ print (stack .is_empty ())
You can’t perform that action at this time.
0 commit comments