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)

200_success
146k22 gold badges190 silver badges479 bronze badges
asked Jun 12, 2018 at 21:13
\$\endgroup\$

1 Answer 1

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

answered Jun 13, 2018 at 8:00
\$\endgroup\$
1
  • \$\begingroup\$ I always forget about module of negative numbers. \$\endgroup\$ Commented Jun 13, 2018 at 8:03

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.