adamthedog adamthedog - 1 year ago 96
Brainfuck Question

Parsing commands+input in BF variant- Python 2.7.12

I'm modifying a Python BrainF*ck interpreter to make my own variant. I'm pretty inexperienced with Python and need some help. In the code, I put in # as well as 0-9 into the filter and added

if command == "#":
cellptr =

to the list of commands. I want the interpreter to read for # and any string of numbers after it. When the string ends, I want the variable
to be changed to the string. How do I do this? The purpose of this is to switch to any cell immediately (Even though it isn't really staying true to the whole point of BF) with the command. Example code:


Add 1 to cell one, 2 to cell two, add 3 to cell three, and jump back to cell one.

Answer Source

Pretty simple. We iterate the rest of the code string to find the number til we hit the end of digits or the end of the code string. Then we set the cell pointer to the new location:

if command == "#":
    num = 0
    codeptr += 1
    while codeptr < len(code) and code[codeptr] in '0123456789':
        num = num * 10 + int(code[codeptr])
        codeptr += 1
    cellptr = num
    codeptr -= 1

(I've decreased the codeptr by one, since you increment it automatically again every time.)

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download