-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtape.py
More file actions
125 lines (105 loc) · 3.23 KB
/
Copy pathtape.py
File metadata and controls
125 lines (105 loc) · 3.23 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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
"""
A Tape
Represents a tape, initialized to 0s with a few functions predefined on it.
"""
class TapeError( Exception ):
pass
class Tape(object):
"""
A Tape Object
This tape object will automatically expand to the right should an
overflow be detected. Default size is 30,000.
"""
def __init__(self, size=None):
"""
Initalize the tape
This tape initially has 30,000 cells and all are 0
"""
if (size==None):
self.tape = [0 for x in range(1,30001,1)]
else:
self.tape = [0 for x in range(1,size,1)]
self.pointer = 0
def increment(self):
"""
Increment the value under the pointer
"""
try:
self.tape[self.pointer]+=1
except:
self.expand()
self.tape[self.pointer]+=1
def decrement(self):
"""
Decrement the value under the pointer
"""
try:
self.tape[self.pointer]-=1
except:
self.expand()
self.tape[self.pointer]-=1
def move_forwards(self):
"""
Move the tape forwards
This actually just increments the internal pointer. Also deals with if the tape is
all used, declares more tape. Doubles the length of the tape when more is needed.
"""
if ((self.pointer) == len(self.tape)):
self.expand()
self.pointer+=1
def move_backwards(self):
"""
Move the tape backwards.
As in the move_forwards, just decrements an internal pointer.
"""
if (self.pointer == 0):
raise TapeError
self.pointer-=1
def replace(self, value=None):
"""
Replace the value of the current cell
The current cell will be replaced the value given. This raises an
error on value not being specified
"""
if (value == None):
raise TapeError
else:
self.tape[self.pointer] = value # No value wrapping to make large
# value calculations easier.
def current_cell(self):
"""
Get the value of the current cell
"""
return self.tape[self.pointer]
def __getitem__(self, i=None):
"""
Get the i-th element of this tape
"""
if (i!=None):
return self.tape[i]
def __eq__(self, other_tape):
"""
Test that this tape is equal to another.
"""
return (self.tape == other_tape.tape)
def __ne__(self, other_tape):
"""
Test if this tape is not equal to another.
"""
return (self.tape != other_tape.tape)
def __len__(self):
"""
Return the length of this tape.
"""
return len(self.tape)
def expand(self):
"""
Double the length of this tape with fresh 0s
"""
self.tape += [0 for x in range(len(self.tape))]
def __str__(self):
"""
Return a string representation of the tape.
First 10 cells.
"""
return self.tape[0:10]