Skip to content

Instantly share code, notes, and snippets.

@phenomist
Created July 8, 2017 01:49
Show Gist options
  • Save phenomist/370cfe1da2ec70db1ba089cb9c421a84 to your computer and use it in GitHub Desktop.
Save phenomist/370cfe1da2ec70db1ba089cb9c421a84 to your computer and use it in GitHub Desktop.
Brainfuck interpreter written in Python - note print buffer is instead returned, so the behavior may be different from programs that run indefinitely long, printing during the program. I also really didn't test input so that might not work.
from collections import Counter as x,deque as y
def interpret(i):
j,u,t,s,g,h,k,r=0,0,x(),{43:(lambda a,b,c,d,e,f:(a+1,b+1,c,d)),45:(lambda a,b,c,d,e,f:(a+1,b-1,c,d)),62:(lambda a,b,c,d,e,f:(a+1,b,c+1,d)),60:(lambda a,b,c,d,e,f:(a+1,b,c-1,d)),46:(lambda a,b,c,d,e,f:(a+1,b,c,d+chr(b))),44:(lambda a,b,c,d,e,f:(a+1,ord(input()[0]),c,d)),91:(lambda a,b,c,d,e,f:(a+1+e*(b==0),b,c,d)),93:(lambda a,b,c,d,e,f:(a+1-f*(b!=0),b,c,d))},x(),x(),y(),""
for e in range(len(i)):
if i[e]=="[":k.append(e)
if i[e]=="]":q=k.pop();h[e]=g[q]=e-q
while j<len(i):j,t[u],u,r=s[ord(i[j])](j,t[u],u,r,g[j],h[j])
return r
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment