-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmystack.py
More file actions
98 lines (78 loc) · 2.5 KB
/
Copy pathmystack.py
File metadata and controls
98 lines (78 loc) · 2.5 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
"""CSC148 Lab 4: Abstract Data Types
Department of Computer Science,
University of Toronto
=== Module Description ===
This module contains an already-implemented Stack class, to be used in
other files, along with a function that uses a Stack.
"""
from typing import Any
from python_ta.contracts import check_contracts
@check_contracts
class Stack:
"""A last-in-first-out (LIFO) stack of items.
Stores data in a last-in, first-out order. When removing an item from the
stack, the most recently-added item is the one that is removed.
Private Attributes:
- _items:
The items stored in this stack. The end of the list represents
the top of the stack.
"""
_items: list[Any]
def __init__(self) -> None:
"""Initialize a new empty stack."""
self._items = []
def is_empty(self) -> bool:
"""Return whether this stack contains no items.
>>> s = Stack()
>>> s.is_empty()
True
>>> s.push('hello')
>>> s.is_empty()
False
"""
return self._items == []
def push(self, item: Any) -> None:
"""Add a new element to the top of this stack."""
self._items.append(item)
def pop(self) -> Any:
"""Remove and return the element at the top of this stack.
Raise an EmptyStackError if this stack is empty.
>>> s = Stack()
>>> s.push('hello')
>>> s.push('goodbye')
>>> s.pop()
'goodbye'
"""
if self.is_empty():
raise EmptyStackError
else:
return self._items.pop()
class EmptyStackError(Exception):
"""Exception raised when an error occurs."""
@check_contracts
def size(s: Stack) -> int:
"""Return the number of items in s.
>>> s = Stack()
>>> size(s)
0
>>> s.push('hi')
>>> s.push('more')
>>> s.push('stuff')
>>> size(s)
3
"""
side_stack = Stack()
count = 0
# Pop everything off <s> and onto <side_stack>, counting as we go.
while not s.is_empty():
side_stack.push(s.pop())
count += 1
# Now pop everything off <side_stack> and back onto <s>.
while not side_stack.is_empty():
s.push(side_stack.pop())
# <s> is restored to its state at the start of the function call.
# We consider that it was not mutated.
return count
if __name__ == '__main__':
import doctest
doctest.testmod(verbose=True)