Last active
August 29, 2015 14:08
-
-
Save retrage/9fbe53ea9ee874d94ec1 to your computer and use it in GitHub Desktop.
Brainf*ck interpreter
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
#!/usr/bin/python | |
from __future__ import print_function | |
import sys | |
if len(sys.argv) > 1: | |
with open(sys.argv[1]) as src: | |
program = src.read() | |
else: | |
print("No input file.") | |
sys.exit(0) | |
inst_ptr = 0 | |
data_ptr = 0 | |
data = [0 for i in range(30000)] | |
inst = program[0] | |
while len(program) > inst_ptr: | |
inst = program[inst_ptr] | |
if inst == '>': | |
data_ptr += 1 | |
elif inst == '<': | |
data_ptr -= 1 | |
elif inst == '+': | |
data[data_ptr] += 1 | |
elif inst == '-': | |
data[data_ptr] -= 1 | |
elif inst == '.': | |
print(chr(data[data_ptr]), end="") | |
elif inst == ',': | |
data[data_ptr] = int(raw_input("-->")) | |
elif inst == '[': | |
if data[data_ptr] == 0: | |
while program[inst_ptr] != ']': | |
inst_ptr += 1 | |
elif inst == ']': | |
if data[data_ptr] != 0: | |
while program[inst_ptr] != '[': | |
inst_ptr -= 1 | |
inst_ptr += 1 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment