-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathinterpreter.py
53 lines (37 loc) · 1.41 KB
/
interpreter.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
51
52
53
def brainfuck_interpreter(code):
memory = [0] * 30000
pointer = 0
output = ""
loop_stack = []
loop_dict = {}
code_ptr = 0
while code_ptr < len(code):
command = code[code_ptr]
if command == '>':
pointer += 1
elif command == '<':
pointer -= 1
elif command == '+':
memory[pointer] = (memory[pointer] + 1) % 256
elif command == '-':
memory[pointer] = (memory[pointer] - 1) % 256
elif command == '.':
output += chr(memory[pointer])
elif command == ',':
pass
elif command == '[':
if memory[pointer] == 0:
code_ptr = loop_dict[code_ptr]
else:
loop_stack.append(code_ptr)
elif command == ']':
if memory[pointer] != 0:
code_ptr = loop_stack[-1] - 1
else:
loop_stack.pop()
code_ptr += 1
return output
if __name__ == "__main__":
brainfuck_code = "-[--->+<]>-.[---->+++++<]>-.+.++++++++++.+[---->+<]>+++.-[--->++<]>-.++++++++++.+[---->+<]>+++.+[----->+<]>+.+.+++++.[---->+<]>+++.[->+++<]>+.-[->+++<]>.[->+++<]>++.[--->+<]>----.+++[->+++<]>++.++++++++.+++++.--------.-[--->+<]>--.+[->+++<]>+.++++++++.-[++>---<]>+.+[->+++<]>.++++++.+++++++.--------.---.+++++++++++++."
output = brainfuck_interpreter(brainfuck_code)
print(output)