Search
 
SCRIPT & CODE EXAMPLE
 

PYTHON

Brainf**k Interpreter in Python

#!/usr/bin/python
#
# Brainfuck Interpreter
# Copyright 2011 Sebastian Kaspari
#
# Usage: ./brainfuck.py [FILE]

import sys
import getch

def execute(filename):
  f = open(filename, "r")
  evaluate(f.read())
  f.close()


def evaluate(code):
  code     = cleanup(list(code))
  bracemap = buildbracemap(code)

  cells, codeptr, cellptr = [0], 0, 0

  while codeptr < len(code):
    command = code[codeptr]

    if command == ">":
      cellptr += 1
      if cellptr == len(cells): cells.append(0)

    if command == "<":
      cellptr = 0 if cellptr <= 0 else cellptr - 1

    if command == "+":
      cells[cellptr] = cells[cellptr] + 1 if cells[cellptr] < 255 else 0

    if command == "-":
      cells[cellptr] = cells[cellptr] - 1 if cells[cellptr] > 0 else 255

    if command == "[" and cells[cellptr] == 0: codeptr = bracemap[codeptr]
    if command == "]" and cells[cellptr] != 0: codeptr = bracemap[codeptr]
    if command == ".": sys.stdout.write(chr(cells[cellptr]))
    if command == ",": cells[cellptr] = ord(getch.getch())
      
    codeptr += 1


def cleanup(code):
  return ''.join(filter(lambda x: x in ['.', ',', '[', ']', '<', '>', '+', '-'], code))


def buildbracemap(code):
  temp_bracestack, bracemap = [], {}

  for position, command in enumerate(code):
    if command == "[": temp_bracestack.append(position)
    if command == "]":
      start = temp_bracestack.pop()
      bracemap[start] = position
      bracemap[position] = start
  return bracemap


def main():
  if len(sys.argv) == 2: execute(sys.argv[1])
  else: print("Usage:", sys.argv[0], "filename")

if __name__ == "__main__": main()
Comment

PREVIOUS NEXT
Code Example
Python :: plot by hour of day pandas 
Python :: how to send one variable to python using xlwings 
Python :: odoo - add one2many field programmatically 
Python :: [Solved]AttributeError: ‘numpy.ndarray’ object has no attribute ‘index’ 
Python :: change set item python 
Python :: u00a0 
Python :: convert timestamp datetime to int no astype 
Python :: locate certs path for python 
Python :: compare if 2 numbers are relatively equal 
Python :: check if cuda is present in torch 
Python :: django query or condition for query parameters 
Python :: wait until exe terminates python 
Python :: task orchestration framework 
Python :: how to print a text in python 
Python :: write to file python 
Python :: python debugger online 
Python :: superpixel 
Python :: is python the best robotic langauge 
Python :: intersection of list of sets 
Python :: pool does not print process id 
Python :: korozif 
Python :: python pipe select where dedup 
Python :: Minimum Number of Operations to Move All Balls to Each Box in python used in function method 
Python :: COLLECTING 
Python :: how to import the whall library in python 
Python :: os.startfile on raspberry 
Python :: pd df pivot 
Python :: dataset.shape 
Python :: python combine if statements 
Python :: pandas add time to datetime 
ADD CONTENT
Topic
Content
Source link
Name
8+8 =