5
\$\begingroup\$

This is another Brainfuck interpreter in Python. I personaly think this is better than most of the other once you find online, because it keeps a bracket_map, which makes both [ and ] instant actions. The data array is a simple defaultdict(int), so it is infinite is size in both directions (which maybe a bad decision?) I am open to all critics and hope that somebody can tell if this is realy as efficient as I think.

from collections import defaultdict
from msvcrt import getch

program = "++++++++++[>+++++++>++++++++++>+++>+<<<<-]>++.>+.+++++++..+++.>++.<<+++++++++++++++.>.+++.------.--------.>+.>."

def evaluate(sourcecode):
    bracket_map = {}
    stack = []
    for i, c in enumerate(sourcecode):
        if c == "[":
            stack.append(i)
        elif c == "]":
            s = stack.pop()
            bracket_map[s], bracket_map[i] = i, s
    assert not stack
    del stack
    data = defaultdict(int)
    data_index = 0
    program_index = 0
    while program_index < len(sourcecode):
        c = sourcecode[program_index]
        if c == "+":
            v = data[data_index] + 1
            if v > 255:
                v = 0
            data[data_index] = v
        elif c == "-":
            v = data[data_index] - 1
            if v < 0:
                v = 255
            data[data_index] = v
        elif c == ">":
            data_index += 1
        elif c == "<":
            data_index -= 1
        elif c == ".":
            print(chr(data[data_index]), end="")
        elif c == ",":
            data[data_index] = getch()[0]
        elif c == "[":
            if not data[data_index]:
                program_index = bracket_map[program_index]
        elif c == "]":
            if data[data_index]:
                program_index = bracket_map[program_index]
        program_index += 1


evaluate(program)

(if you are not on windows, you need an alternative for the getch function)

\$\endgroup\$
1
\$\begingroup\$

All in all this looks good to me. I would make 2 changes

bracket_map

The code to assemble this map can be more clear in it's own function.

+ and -

v = data[data_index] - 1
if v < 0:
    v = 255
data[data_index] = v

can be easily replaced by

data[data_index] = (data[data_index] - 1) % 256

Same goes for the + operation

\$\endgroup\$
  • \$\begingroup\$ I always forget about module of negative numbers. \$\endgroup\$ – MegaIng Jun 13 '18 at 8:03

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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