-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstack.py
More file actions
53 lines (41 loc) · 1.49 KB
/
stack.py
File metadata and controls
53 lines (41 loc) · 1.49 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
#!usr/bin/env python3
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.
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 method returns the last item in the list,
which is also the item at the top of the Stack.
This method runs in constant time because indexing
into a list is done 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 method 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 for equality happens in constant time.
"""
return self.items == []