1
1
from __future__ import annotations
2
2
3
+ from typing import Generic , TypeVar
4
+
5
+ T = TypeVar ("T" )
6
+
3
7
4
8
class StackOverflowError (BaseException ):
5
9
pass
@@ -9,7 +13,7 @@ class StackUnderflowError(BaseException):
9
13
pass
10
14
11
15
12
- class Stack :
16
+ class Stack ( Generic [ T ]) :
13
17
"""A stack is an abstract data type that serves as a collection of
14
18
elements with two principal operations: push() and pop(). push() adds an
15
19
element to the top of the stack, and pop() removes an element from the top
@@ -19,7 +23,7 @@ class Stack:
19
23
"""
20
24
21
25
def __init__ (self , limit : int = 10 ):
22
- self .stack : list [int ] = []
26
+ self .stack : list [T ] = []
23
27
self .limit = limit
24
28
25
29
def __bool__ (self ) -> bool :
@@ -28,13 +32,13 @@ def __bool__(self) -> bool:
28
32
def __str__ (self ) -> str :
29
33
return str (self .stack )
30
34
31
- def push (self , data ) :
35
+ def push (self , data : T ) -> None :
32
36
"""Push an element to the top of the stack."""
33
37
if len (self .stack ) >= self .limit :
34
38
raise StackOverflowError
35
39
self .stack .append (data )
36
40
37
- def pop (self ):
41
+ def pop (self ) -> T :
38
42
"""
39
43
Pop an element off of the top of the stack.
40
44
@@ -47,7 +51,7 @@ def pop(self):
47
51
raise StackUnderflowError
48
52
return self .stack .pop ()
49
53
50
- def peek (self ):
54
+ def peek (self ) -> T :
51
55
"""
52
56
Peek at the top-most element of the stack.
53
57
@@ -71,7 +75,7 @@ def size(self) -> int:
71
75
"""Return the size of the stack."""
72
76
return len (self .stack )
73
77
74
- def __contains__ (self , item ) -> bool :
78
+ def __contains__ (self , item : T ) -> bool :
75
79
"""Check if item is in stack"""
76
80
return item in self .stack
77
81
@@ -80,7 +84,7 @@ def test_stack() -> None:
80
84
"""
81
85
>>> test_stack()
82
86
"""
83
- stack = Stack (10 )
87
+ stack : Stack [ int ] = Stack (10 )
84
88
assert bool (stack ) is False
85
89
assert stack .is_empty () is True
86
90
assert stack .is_full () is False
0 commit comments