-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathListStack.py
More file actions
80 lines (70 loc) · 2.48 KB
/
Copy pathListStack.py
File metadata and controls
80 lines (70 loc) · 2.48 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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
class ListStack:
'''
This is a list based implementation of a stack which will keep newest data
and drop anything oldest that there is not room for
'''
def __init__(self, capacity):
# create list of size capacity
self.list_stack = [None] * capacity
# store as instance variable
self._capacity = capacity
# set other instance variable defaults
self.top = -1
self.size = 0
def __str__(self):
# pretty print
result = 'ListStack['
for val in self.list_stack[self.top::-1]:
result += ' ' + str(val)
for val in self.list_stack[-1:self.top:-1]:
result += ' ' + str(val)
return result + ']'
def insert(self, val):
# update pointers during insert to keep only newest data
self.top += 1
if self.top == self._capacity:
self.top = 0
self.list_stack[self.top] = val
self.size += 1
def remove(self):
# no op if empty
if self.size is 0:
return
# update pointers
self.list_stack[self.top] = None
self.top -= 1
if self.top is -1:
self.top = self._capacity - 1
def peek(self):
return self.list_stack[self.top]
def capacity(self):
return self._capacity
def test():
print('Creating empty ListStack named "a" of size 3')
a = ListStack(3)
print('Creating empty ListStack named "b" of size 2')
b = ListStack(2)
print('peek on a', a.peek(), 'currently contains', a)
print('peek on b', a.peek(), 'currently contains', b)
for val in range(3):
print('inserting', val, 'into both a and b')
a.insert(val)
# won't fit all
b.insert(val)
print('peek on a', a.peek(), 'currently contains', a)
print('peek on b', a.peek(), 'currently contains', b)
for i in range(2):
print('removing', a.peek(), 'from a')
a.remove()
print('peek on a', a.peek(), 'currently contains', a)
print('removing', b.peek(), 'from b')
b.remove()
print('peek on b', a.peek(), 'currently contains', b)
for val in range(2):
print('inserting', val, 'into both a and b')
a.insert(val)
b.insert(val)
print('peek on a', a.peek(), 'currently contains', a)
print('peek on b', a.peek(), 'currently contains', b)
if __name__ == '__main__':
test()