-
Notifications
You must be signed in to change notification settings - Fork 0
/
stack.py
135 lines (100 loc) · 3.07 KB
/
stack.py
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
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
class StackEmptyError(IndexError):
"""Attempt to pop an empty stack."""
class Stack(object):
"""LIFO stack.
Implemented using a Python list; since stacks just need
to pop and push, a list is a good implementation, as
these are O(1) for native Python lists. However, in cases
where performance really matters, it might be best to
use a Python list directly, as it avoids the overhead
of a custom class.
Or, for even better performance (& typically smaller
memory footprint), you can use the `collections.deque`
object, which can act like a stack.
(We could also write our own LinkedList class for a
stack, where we push things onto the head and pop things
off the head (effectively reversing it), but that would be less
efficient than using a built-in Python list or a
`collections.deque` object)
"""
def __init__(self):
self._list = []
def __repr__(self):
if not self._list:
return "<Stack (empty)>"
else:
return "<Stack tail=%s length=%d>" % (
self._list[-1], len(self._list))
def push(self, item):
"""Add item to end of stack."""
self._list.append(item)
def pop(self):
"""Remove item from end of stack and return it."""
if not self._list:
raise StackEmptyError()
return self._list.pop()
def __iter__(self):
"""Allow iteration over list.
__iter__ is a special method that, when defined,
allows you to loop over a list, so you can say things
like "for item in my_stack", and it will pop
successive items off.
"""
while True:
try:
yield self.pop()
except StackEmptyError:
raise StopIteration
def length(self):
"""Return length of stack::
>>> s = Stack()
>>> s.length()
0
>>> s.push("dog")
>>> s.push("cat")
>>> s.push("fish")
>>> s.length()
3
"""
if not self._list:
return 0
else:
return len(self._list)
def empty(self):
"""Empty stack::
>>> s = Stack()
>>> s.push("dog")
>>> s.push("cat")
>>> s.push("fish")
>>> s.length()
3
>>> s.empty()
>>> s.length()
0
"""
if not self._list:
return "There is nothing to empty."
else:
del self._list[:]
def is_empty(self):
"""Is stack empty?
>>> s = Stack()
>>> s.is_empty()
True
>>> s.push("dog")
>>> s.push("cat")
>>> s.push("fish")
>>> s.is_empty()
False
"""
if self._list:
return False
else:
return True
if __name__ == "__main__":
import doctest
print
result = doctest.testmod()
if not result.failed:
print "ALL TESTS PASSED. GOOD WORK!"
print