-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstack.py
More file actions
79 lines (59 loc) · 1.97 KB
/
stack.py
File metadata and controls
79 lines (59 loc) · 1.97 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
class StackOverflow(Exception):
pass
class StackUnderflow(Exception):
pass
class Stack:
def __init__(self):
# preallocated
self.items = [0] * 128
self.current = -1
def pop(self):
if self.current <= -1:
raise StackUnderflow('stack underflow')
elif self.current > len(self.items) - 1:
raise StackOverflow('stack overflow')
else:
ret = self.items[self.current]
self.current -= 1
return ret
def push(self, i):
self.items[self.current + 1] = i
self.current += 1
def append(self, *args):
return self.push(*args)
def __len__(self):
return len(self.items)
def __str__(self):
return str(self.items[:max(0, self.current + 1)])
def __repr__(self):
return self.__str__()
def __eq__(self, other):
return self.items[:max(0, self.current + 1)] == other.items[:max(0, self.current + 1)]
class MappedStack:
def __init__(self, memory, stack_bottom, size=None):
self.memory = memory
self.bottom = stack_bottom
self.current = self.bottom
self.size = size or stack_bottom
def pop(self):
if self.current >= self.bottom:
raise StackUnderflow('stack underflow')
ret = self.memory[self.current]
self.current += 1
return ret
def push(self, i):
if self.current <= self.bottom - self.size:
raise StackOverflow('stack overflow')
self.memory[self.current - 1] = i
self.current -= 1
def append(self, *args):
return self.push(*args)
def list(self):
return self.memory[self.current:self.bottom][::-1]
def __str__(self):
return str(self.memory[self.current:self.bottom][::-1])
def __repr__(self):
return self.__str__()
def __eq__(self, other):
return self.memory[self.current:self.bottom] == \
other.memory[self.current:self.bottom]