Skip to content

Instantly share code, notes, and snippets.

@retrage
Last active August 29, 2015 14:10
Show Gist options
  • Save retrage/5bb0868ef52e39db09b3 to your computer and use it in GitHub Desktop.
Save retrage/5bb0868ef52e39db09b3 to your computer and use it in GitHub Desktop.
Brainf*ck like stack machine interpreter
#!/usr/bin/python
from __future__ import print_function
import sys
if len(sys.argv[1]) > 1:
with open(sys.argv[1]) as src:
program = src.read()
else:
print("No input file.")
sys.exit(0)
inst_ptr = 0
stck_ptr = 0
stck = [0]
inst = program[0]
while len(program) > inst_ptr:
inst = program[inst_ptr]
if inst == '>':
stck.append(0)
elif inst == '<':
del stck[-1]
elif inst == '+':
stck[-2] += stck[-1]
del stck[-1]
elif inst == '-':
stck[-2] -= stck[-1]
del stck[-1]
elif inst == '.':
print(chr(stck[-1]), end="")
del stck[-1]
elif inst == ',':
stck.append(0)
stck[-1] = int(raw_input("-->"))
elif inst == '[':
if stck[-1] == 0:
while program[inst_ptr] != ']':
inst_ptr += 1
elif inst == ']':
if stck[-1] != 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