-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBrainFuck_Interpreter.py
More file actions
78 lines (54 loc) · 1.81 KB
/
Copy pathBrainFuck_Interpreter.py
File metadata and controls
78 lines (54 loc) · 1.81 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
from __future__ import print_function
import sys
class Brainfuck:
def __init__(self, src):
self.src = self.clean(list(src))
self.stack = [0]*2
self.ptr = 0
self.code_ptr = 0
self.open_bracket_indexes = []
self.close_bracket_indexes = []
self.pair_brackets()
def clean(self, code):
return ''.join(filter(lambda x:x in ['+','-','.',',','[',']','>','<'], code))
def pair_brackets(self):
"""
_open_bracket_indexes[i] is paired with _close_bracket_indexes[i].
"""
stack = []
for index, command in enumerate(self.src):
if command == '[':
stack.append(index)
elif command == ']':
self.open_bracket_indexes.append(stack.pop())
self.close_bracket_indexes.append(index)
def evaluate(self):
while self.code_ptr < len(self.src):
command = self.src[self.code_ptr]
if command == '+':
self.stack[self.ptr] += 1 if self.stack[self.ptr] < 255 else 0
elif command == '-':
self.stack[self.ptr] -= 1 if self.stack[self.ptr] > 0 else 255
elif command == '>':
self.ptr += 1
if self.ptr > len(self.stack)-1:
self.stack.append(0)
elif command == '<':
self.ptr -= 1 if self.ptr > 0 else 0
elif command == '.':
print(chr(self.stack[self.ptr]),end = '')
elif command == ',':
self.stack[self.ptr] = ord(sys.stdin.read(1))
elif command == ']' and self.stack[self.ptr] != 0:
index = self.close_bracket_indexes.index(self.code_ptr)
self.code_ptr = self.open_bracket_indexes[index]
elif command == '[' and self.stack[self.ptr] == 0:
index = self.open_bracket_indexes.index(self.code_ptr)
self.code_ptr = self.close_bracket_indexes[index]
self.code_ptr += 1
def main():
src = open(sys.argv[1], 'r').read()
bf = Brainfuck(src)
bf.evaluate()
if __name__ == '__main__':
main()