-
Notifications
You must be signed in to change notification settings - Fork 0
/
Interpreter_Python_version.py
80 lines (61 loc) · 1.96 KB
/
Interpreter_Python_version.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
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
###########################
# Has some freaking error #
###########################
def main(code):
legalCharacters=['+', '-', '>', '<', '.', ',', '[', ']']
tokens=[]
looper=0
for char in code:
if char in legalCharacters:
tokens.append(char)
if char == '[':
looper += 1
if char == ']':
looper -= 1
if looper != 0:
raise Exception("The number of '[' is not equal to the number of ']'")
interpret(tokens)
def interpret(tokens):
memory = [0 for i in range(30_000)]
pointer=0
isLooping=False
loopStack=[]
innerLoops=0
for i in range(len(tokens)):
brainfToken = tokens[i]
if isLooping:
if brainfToken == '[':
innerLoops += 1
if brainfToken == ']':
if innerLoops == 0:
isLooping = False
else:
innerLoops -= 1
continue
if brainfToken == '+':
memory[pointer] += 1
elif brainfToken == '-':
memory[pointer] -= 1
elif brainfToken == '>':
pointer += 1
elif brainfToken == '<':
pointer -= 1
if pointer < 0:
raise ValueError('Pointer value less than 0 is not allowed')
elif brainfToken == ',':
memory[pointer]=ord(input()[0])
elif brainfToken == '.':
print(chr(memory[pointer]))
elif brainfToken == '[':
if memory[pointer] == 0:
isLooping = True
else:
loopStack.append(i)
elif brainfToken == ']':
if memory[pointer] != 0:
i = loopStack[-1]
else:
loopStack.pop()
if __name__ == "__main__":
with open("brainf.txt") as file:
main(file.read())