-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathstack.py
More file actions
103 lines (91 loc) · 2.35 KB
/
stack.py
File metadata and controls
103 lines (91 loc) · 2.35 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
from typing import Any
class Stack:
def __init__(self, capacity: int = 10) -> None:
self.stack = []
self.capacity = capacity
def __len__(self):
"""
>>> stack = Stack()
>>> for i in range(0, 10):
... stack.push(i)
>>> len(stack)
10
"""
return len(self.stack)
def size(self) -> int:
"""
>>> stack = Stack()
>>> for i in range(0, 10):
... assert len(stack) == i
... stack.push(i)
>>> stack.size()
10
"""
return len(self)
def is_full(self) -> bool:
"""
>>> stack = Stack()
>>> for i in range(0, 10):
... stack.push(i)
>>> stack.is_full()
True
"""
return len(self) == self.capacity
def is_empty(self) -> bool:
"""
>>> stack = Stack()
>>> stack.is_empty()
True
>>> stack.push(666)
>>> stack.push(999)
>>> stack.is_empty()
False
"""
return len(self) == 0
def push(self, item: Any) -> None:
"""
>>> stack = Stack()
>>> for i in range(0, 10):
... stack.push(i)
>>> stack.push(666)
Traceback (most recent call last):
...
ValueError: stack is full
"""
if self.is_full():
raise ValueError("stack is full")
self.stack.append(item)
def pop(self) -> Any:
"""
>>> stack = Stack()
>>> stack.pop()
Traceback (most recent call last):
...
ValueError: stack is empty
>>> for i in range(0, 10):
... stack.push(i)
>>> for i in range(9, -1, -1):
... assert stack.pop() == i
"""
if self.is_empty():
raise ValueError("stack is empty")
return self.stack.pop()
def peek(self) -> Any:
"""
>>> stack = Stack()
>>> stack.peek()
Traceback (most recent call last):
...
ValueError: stack is empty
>>> stack.push('a')
>>> stack.push('b')
>>> stack.push('c')
>>> stack.peek()
'c'
"""
if self.is_empty():
raise ValueError("stack is empty")
return self.stack[-1]
if __name__ == "__main__":
from doctest import testmod
testmod()