Created
May 23, 2011 14:37
-
-
Save kates/986792 to your computer and use it in GitHub Desktop.
brainfuck interpreter in python
This file contains hidden or 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
""" | |
bf.py | |
Brainfuck interpreter written in python. | |
Does not handle input :( | |
""" | |
import sys | |
def run(src): | |
c = [0] * 30000 | |
p = 0 | |
loop = [] | |
rv = [] | |
ts = list(src) | |
l = len(ts) | |
i = 0; | |
while i < l: | |
t = ts[i] | |
if t == ">": p += 1 | |
elif t == "<": p -= 1 | |
elif t == "+": c[p] += 1 | |
elif t == "-": c[p] -= 1 | |
elif t == ".": rv.append(chr(c[p])) | |
elif t == ",": pass | |
elif t == "[": | |
if c[p] == 0: | |
while ts[i] != "]": i += 1 | |
loop.pop() | |
else: | |
loop.append(i - 1) | |
elif t == "]": i = loop[-1] | |
i += 1 | |
print "".join(rv) | |
def parse_args(): | |
if len(sys.argv) == 1: | |
print_usage() | |
else: | |
run(sys.argv[1]) | |
def print_usage(): | |
print "Usage:\n\t%s '<source>'" % sys.argv[0] | |
if __name__ == "__main__": | |
parse_args() |
It works with input()
source = input()
def run(src):
c = [0] * 30000
p = 0
loop = []
rv = []
ts = list(src)
l = len(ts)
i = 0
while i < l:
t = ts[i]
if t == ">": p += 1
elif t == "<": p -= 1
elif t == "+": c[p] += 1
elif t == "-": c[p] -= 1
elif t == ".": rv.append(chr(c[p]))
elif t == ",": pass
elif t == "[":
if c[p] == 0:
while ts[i] != "]": i += 1
loop.pop()
else:
loop.append(i - 1)
elif t == "]": i = loop[-1]
i += 1
print("".join(rv))
def parse_source():
run(source)
if __name__ == "__main__":
parse_source()
This doesn't seem to work with nested loops
I think this is a better sulotion:https://github.com/pocmo/Python-Brainfuck/blob/master/brainfuck.py
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This doesn't seem to work with nested loops