Take the 2-minute tour ×
Code Review Stack Exchange is a question and answer site for peer programmer code reviews. It's 100% free, no registration required.

I was bored, so I wrote a BrainFuck interpreter in Python. It essentially takes input for the amount of cells, then parses the inputted code through a series of if statements.

# Simple BrainFuck interpreter
from sys import exit

# Main interpreter function
def interpreter(cell_amount):
    step = 0
    cell = [0] * cell_amount
    cell_pos = 0 
    loop = False
    loop_ret = 0

    code_input = raw_input('Code: ') 
    steps = len(code_input)

    while True:

        if code_input[step] == '+':
            cell[cell_pos] += 1

        elif code_input[step] == '-': 
            cell[cell_pos] -= 1

        elif code_input[step] == '>':
            cell_pos += 1

        elif code_input[step] == '<':
            cell_pos -= 1

        elif code_input[step] == '[':
            if loop == False:
                loop_ret = step
                loop = True

        elif code_input[step] == ']':
            if cell[cell_pos] != 0:
                step = loop_ret
            elif cell[cell_pos] == 0:
                loop = False

        elif code_input[step] == '.':
            print str(cell[cell_pos])

        elif code_input[step] == ',':
            cell[cell_pos] = int(raw_input())

        step += 1

        if step == steps:
            exit(0)

interpreter(int(raw_input('Cell amount: ')))

Now, it works, with one small issue: loops can't be nested. I'd like a few things to be improved about it.

  • Read code from a text file instead of stdin.
  • Better system than a chain of if/elif/else statements.
  • Be able to nest loops.
share|improve this question
7  
Please note, if you're asking how your code should be modified to support nested loops or reading from a file, ...that's changing what the code does, not how it's doing it. –  Mat's Mug Jul 25 at 18:16

1 Answer 1

up vote 5 down vote accepted

This being Python, it should be relatively easy to present the illusion of an infinite tape, at least in the positive direction. I don't see reason that cell_amount has to be specified, and the user shouldn't have to worry about such details.

Your input and output routines are wrong:

  • The . instruction should print one character, interpreting the cell value as an ASCII code. Instead, you print the cell value as a base-10 number, followed by Newline.
  • The , instruction should read one character, storing its ASCII code as the cell value. Instead, you read a string, and try to parse it as an integer.

while True: … is a lie. What you really mean is while step < steps: …. Then you can get rid of the if step == steps: exit(0) at the end of the loop.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.