I am attempting to implement an interpreter for brainfuck and as of now, I am just using a series of if/elif statements.

if(i == ">"):
    ...
elif(i == "<"):
    ...
elif(i == "+"):
    ...
elif(i == "-"):
    ...

However, this seems very clunky and un-pythonic to me. Is there a better (cleaner/faster/more aesthetically pleasing) way to implement this?

有帮助吗?

解决方案

I have a quick implementation of a Brainfuck interpreter for Python in a GitHub repo. In a nutshell, though, you could keep a dictionary, where the keys are the Brainfuck characters and the values are function (or method) objects, and then dispatch on that. Something like this:

instructions = {
  '+': increment,
  '-': decrement,
  # Other functions
}

def run(tape):
  ch = next_token(tape)
  if ch in instructions:
    instructions[ch]()

(Not an actual implementation, just a quick illustration.)

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top