Created
August 27, 2019 15:47
-
-
Save melwyn95/4c1cdd2a7a091f9d7d71fb63b6172bb0 to your computer and use it in GitHub Desktop.
BrainFuck Interpreter in Python
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
valid_commands = ['>', '<', '+', '-', '[', ']', ',', '.'] | |
clean = lambda raw_script: list(filter(lambda x: x in valid_commands, raw_script)) | |
def parse_square_brackets(script): | |
stack = [] | |
brackets_map = {} | |
for index, command in enumerate(script): | |
if command == '[': | |
stack.append(index) | |
brackets_map[index] = None | |
elif command == ']': | |
bracket_start_index = stack.pop(len(stack) - 1) | |
brackets_map[index] = bracket_start_index | |
brackets_map[bracket_start_index] = index | |
return brackets_map | |
def execute_command(command, code_pointer, brackets_map, tape, data_pointer): | |
if command == '>': data_pointer += 1 | |
elif command == '<': data_pointer -= 1 | |
elif command == '+': tape[data_pointer] += 1 | |
elif command == '-': tape[data_pointer] -= 1 | |
elif command == '[': | |
if tape[data_pointer] == 0: | |
code_pointer = brackets_map[code_pointer] | |
elif command == ']': | |
if tape[data_pointer] > 0: | |
code_pointer = brackets_map[code_pointer] | |
elif command == '.': print (chr(tape[data_pointer])) | |
elif command == ',': tape[data_pointer] = ord(input('i/p: ')) | |
return code_pointer + 1, data_pointer, tape | |
while True: | |
tape = [0 for _ in range(30000)] | |
data_pointer = 0 | |
script = clean(list(input('yo: '))) | |
script_length = len(script) | |
brackets_map = parse_square_brackets(script) | |
code_pointer = 0 | |
while code_pointer < script_length: | |
command = script[code_pointer] | |
code_pointer, data_pointer, tape = execute_command(command, code_pointer, brackets_map, tape, data_pointer) | |
print (tape[:17]) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment