-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy paththree_in_one.py
72 lines (56 loc) · 2 KB
/
three_in_one.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
# 3.1: Three in One
from sq_exceptions import StackEmptyException, StackFullException
class FixedMultiStack:
def __init__(self, capacity):
self.num_stacks = 3
self.capacity = capacity
self.values = [0] * (self.capacity * self.num_stacks)
self.sizes = [0] * self.num_stacks
# Runtime: O(1) - Space: O(1)
def push(self, stack_num: int, item: int) -> None:
if self.is_full(stack_num):
raise StackFullException("Stack is full!")
self.sizes[stack_num] += 1
idx = self.index_of_top(stack_num)
self.values[idx] = item
# Runtime: O(1) - Space: O(1)
def pop(self, stack_num: int) -> int:
if self.is_empty(stack_num):
raise StackEmptyException("Stack has nothing to pop!")
idx = self.index_of_top(stack_num)
item = self.values[idx]
self.values[idx] = 0
self.sizes[stack_num] -= 1
return item
# Runtime: O(1) - Space: O(1)
def peek(self, stack_num: int) -> int:
if self.is_empty(stack_num):
raise StackEmptyException("Stack is empty. Nothing to peek at!")
idx = self.index_of_top(stack_num)
return self.values[idx]
# Runtime: O(1) - Space: O(1)
def is_empty(self, stack_num: int) -> bool:
return self.sizes[stack_num] == 0
# Runtime: O(1) - Space: O(1)
def is_full(self, stack_num: int) -> bool:
return self.sizes[stack_num] == self.capacity
# Runtime: O(1) - Space: O(1)
def size(self, stack_num: int) -> int:
return self.sizes[stack_num]
# Runtime: O(1) - Space: O(1)
def index_of_top(self, stack_num: int) -> int:
offset = stack_num * self.capacity
size = self.sizes[stack_num]
return offset + size - 1
stack = FixedMultiStack(3)
stack.push(0, 5)
print(stack.peek(0))
stack.push(0, 3)
print(stack.pop(0))
print(stack.is_empty(0))
print(stack.is_full(0))
stack.push(0, 1)
stack.push(0, 2)
print(stack.size(0))
print(stack.is_empty(0))
print(stack.is_full(0))