-
Notifications
You must be signed in to change notification settings - Fork 3
/
bf.py
58 lines (53 loc) · 1.51 KB
/
bf.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
from collections import defaultdict, Counter
import sys
brainFuck = str(sys.stdin.read())
valid = "><+-,.[]"
def parse(brainFuck):
leftCounter = rightCounter = 0
brackets = {}
parsedInput = ''.join([char for char in brainFuck if char in valid])
for key,char in enumerate(parsedInput):
if char == "[":
leftCounter += 1
rightCounter = leftCounter
brackets[key] = leftCounter
elif char == "]":
while rightCounter in [x for x, y in Counter(brackets.values()).items() if y > 1]:
rightCounter -= 1
brackets[key] = rightCounter
bracketList = defaultdict(list)
for k, v in brackets.items():
bracketList[v].append(k)
bracketList = list(dict(bracketList).values())
for subList in bracketList:
subList.sort()
return parsedInput, bracketList
def main(args):
parsedInput = args[0]
brackets = args[1]
counter = tapeCounter = 0
tape = [0]*30000
while counter < len(parsedInput):
char = parsedInput[counter]
if char == ">":
tapeCounter +=1
elif char == "<":
tapeCounter -=1
elif char == "+":
tape[tapeCounter] += 1
elif char == "-":
tape[tapeCounter] -= 1
elif char == ",":
tape[tapeCounter] = ord(input("Enter: ")[0])
elif char == ".":
print(chr(tape[tapeCounter]))
elif char == "[" and tape[tapeCounter] == 0:
key = [y[0] for y in brackets].index(counter)
counter = brackets[key][1]
continue
elif char == "]" and tape[tapeCounter] != 0:
key = [y[1] for y in brackets].index(counter)
counter = brackets[key][0]
continue
counter+=1
main(parse(brainFuck))