-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstack.py
56 lines (41 loc) · 1.51 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
class Stack:
def __init__(self):
self.items = []
def push (self, item):
""" Accepts an item as a parameter and appends it to the end of the list
Returns nothing
The runtime for this method is O(1), or constant time, because appending
to the end of a list happens in constant time
"""
self.items.append(item)
def pop(self):
""" Removes and returns the last item for the list, which is also the
top item of the Stack
The runtime here is constant time, because all it does is index to the
last item of the list.
"""
if self.items:
return self.items.pop()
return None
def peek(self):
""" This methods returns the last item in the list, which is also the item
at the top of Stack
This method runs in constant time because indexing in the list dones in
constant time.
"""
if self.items:
return self.items[-1]
return None
def size(self):
""" This method returns the length of the list that is representing the
Stack.
This methods runs in constant time because finding the length of a list
also in constant time.
"""
return len(self.items)
def is_empty(self):
"""This method returns a Boolean value describing whether or not the Stack
is empty.
Testing the quality happens in constant time.
"""
return self.items == []