Skip to content

Instantly share code, notes, and snippets.

@kates
Created May 23, 2011 14:37
Show Gist options
  • Save kates/986792 to your computer and use it in GitHub Desktop.
Save kates/986792 to your computer and use it in GitHub Desktop.
brainfuck interpreter in python
"""
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()
@bkrmendy
Copy link

This doesn't seem to work with nested loops

@bronekalmar
Copy link

bronekalmar commented Sep 12, 2017

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()

@cleiveliu
Copy link

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