-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstack.py
67 lines (54 loc) · 1.57 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
from datastructures_and_algorithms.exceptions.StackEmptyException import StackEmptyException
class Stack:
def __init__(self):
self._data = list()
def __len__(self):
"""
0(n)
Provides the length of Stack as the length of the list() in self._data
:return: int length
"""
return len(self._data)
def __reversed__(self):
"""
0(n)
Reverses the items in the Stack
:return: New Stack, reversed order from original
"""
newlist = self._data[::-1]
self._data = newlist
def __iter__(self):
i = 0
current = self._data[i]
for i in self:
yield current
i += 1
def push(self, item):
"""
0(1)
Adds an item to the Stack
:param item: The value of the item wished to be added to the stack.
:return: Nothing
"""
self._data.append(item)
def pop(self):
"""
0(n) - due to len (could use try/except block for 0(1) instead
Takes top item on stack off the stack.
:return: top list item in Stack
"""
if len(self) == 0:
return None
item = self._data[-1]
del self._data[-1]
return item
def peek(self):
"""
0(n) - same as above
Takes the top item on the stack, without deleting it
:return: top list item in Stack
"""
if len(self) < 1:
raise StackEmptyException("Can't peek an empty stack")
item = self._data[-1]
return item