1 Replies - 2066 Views - Last Post: 09 May 2012 - 02:11 PM

#1 Dogstopper   User is offline

  • The Ninjaducky
  • member icon

Reputation: 2972
  • View blog
  • Posts: 11,223
  • Joined: 15-July 08

BrainF**k Interpreter

Posted 10 May 2011 - 02:40 AM

Description: Pass a BrainF**k program to the interpret method:

program = "++++++++++[>+++++++>++++++++++>+++>+<<<<-]>++.>+.+++++++..+++.>++.<<+++++++++++++++.>.+++.------.--------.>+.>."
interpret(program)


This snippet interprets and excutes BrainF**k code instead of compiling it to another state.
# BrainF**k interpreter
from __future__ import print_function

def interpret(program):

    # Starting variables
    program = str(program)
    data = [0 for x in range(30000)]

    ptr = 0
    sPos = 0
    loop_locs = []
    

    # Iterate through each character and act
    # based on the operation
    while sPos < len(program):
        character = program[sPos]
        if character is '>':
            ptr += 1
        elif character is '<':
            ptr -= 1
        elif character is '+':
            data[ptr] += 1
        elif character is '-':
            data[ptr] -= 1
        elif character is '.':
            print(chr(data[ptr]), end='')
        elif character is ',':
            data[ptr] = ord(raw_input()[0])
        elif character is '[':
            loop_locs.append(sPos)
            end_brace = getMatchingBrace(program, sPos)

            if data[ptr] == 0:
                if end_brace == -1:
                    print("Syntax Error: No matching end brace.")
                else:
                    sPos = end_brace;
        elif character is ']':
            if len(loop_locs) == 0:
                print("Syntax Error: No starting brace.")
            if data[ptr] != 0:
                sPos = loop_locs[-1]
            else:
                loop_locs.pop()

        sPos += 1

def getMatchingBrace(program, sPos):
    matches = 1
    for x in range(sPos, len(program)):
        if program[x] is '[':
            matches += 1
        elif program[x] is ']':
            matches -= 1
            if matches == 0:
                return x
    return -1




Is This A Good Question/Topic? 1
  • +

Replies To: BrainF**k Interpreter

#2 atraub   User is offline

  • Pythoneer
  • member icon

Reputation: 830
  • View blog
  • Posts: 2,251
  • Joined: 23-December 08

Re: BrainF**k Interpreter

Posted 09 May 2012 - 02:11 PM

Why would anyone vote this less than a 5?
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1