-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstack_array.py
More file actions
59 lines (49 loc) · 1.96 KB
/
Copy pathstack_array.py
File metadata and controls
59 lines (49 loc) · 1.96 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
class Stack:
'''Implements an efficient last-in first-out Abstract Data Type using a Python List'''
def __init__(self, capacity):
'''Creates and empty stack with a capacity'''
self.capacity = capacity
self.items = [None]*capacity
self.num_items = 0
def is_empty(self):
if self.capacity == 0:
return False
return self.num_items == 0
# '''Returns True if the stack is empty, and False otherwise
# MUST have O(1) performance'''
def is_full(self):
return self.num_items == self.capacity
# '''Returns True if the stack is full, and False otherwise
# MUST have O(1) performance'''
def push(self, item):
if self.is_full():
raise IndexError
else:
self.items[self.num_items] = item
self.num_items += 1
# '''If stack is not full, pushes item on stack.
# If stack is full when push is attempted, raises IndexError
# MUST have O(1) performance'''
def pop(self):
if self.is_empty():
raise IndexError
else:
current_item = self.items[self.num_items - 1]
self.items[self.num_items - 1] = None
self.num_items -= 1
return current_item
# '''If stack is not empty, pops item from stack and returns item.
# If stack is empty when pop is attempted, raises IndexError
# MUST have O(1) performance'''
def peek(self):
if self.is_empty():
raise IndexError
else:
return self.items[self.num_items - 1]
# '''If stack is not empty, returns next item to be popped (but does not pop the item)
# If stack is empty, raises IndexError
# MUST have O(1) performance'''
def size(self):
return self.num_items
# '''Returns the number of elements currently in the stack, not the capacity
# MUST have O(1) performance'''