-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathintcode_memory.py
52 lines (40 loc) · 1.33 KB
/
intcode_memory.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
class IntcodeMemory(list):
DEFAULT_VALUE = 0
"""
Subclass of list that defaults to a value of 0 and can extend to an
infinite size. Negative values and slice access are forbidden.
"""
def __init__(self, code=[]):
# Initialse ourselves with code
self += code
def __fill(self, index):
"fill memory with zeroes up to index"
self += ([self.DEFAULT_VALUE] * (index - len(self) + 1))
def __setitem__(self, index, value):
if isinstance(index, slice):
raise Exception("slice access")
if index < 0:
raise Exception("negative memory access")
self.__fill(index)
list.__setitem__(self, index, value)
def __getitem__(self, index):
if isinstance(index, slice):
raise Exception("slice access")
if index < 0:
raise Exception("negative memory access")
if index >= len(self):
return self.DEFAULT_VALUE
else:
return list.__getitem__(self, index)
def __add__(self, other):
if isinstance(other, list):
r = self.copy()
r += other
return r
else:
return list.__add__(self, other)
def copy(self):
"Return a shallow copy of the list"
r = IntcodeMemory()
r += self
return r