MaoKwen
7/20/2019 - 2:25 PM

brainfuck.py

import sys

# hello = "++++++++[>++++[>++>+++>+++>+<<<<-]>+>+>->>+[<]<-]>>.>---.+++++++..+++.>>.<-.<.+++.------.--------.>>+.>++."

def cleanup(input):
    return ''.join(list(filter(lambda c: c in ['>', '<', '+', '-', '.', ',', '[', ']'], input)))


class stream(list):
    def expand(self, index):
        if index >= len(self):
            self.extend([0]*(index+1-len(self)))

    def __getitem__(self, index):
        self.expand(index)
        return list.__getitem__(self, index)

    def __setitem__(self, index, value):
        self.expand(index)
        list.__setitem__(self, index, value)


def main(argv=sys.argv):
    code, code_p = cleanup(argv[1]), 0
    cell, cell_p = stream(), 0
    code_len = len(code)
    while code_p < code_len:
        op = code[code_p]
        if op == '>': cell_p += 1
        if op == '<': cell_p -= 1
        if op == '+': cell[cell_p] += 1
        if op == '-': cell[cell_p] -= 1
        if op == '.': print(chr(cell[cell_p]), end='')
        if op == ',': cell[cell_p] = sys.stdin.read(1)
        if op == '[' :
            if cell[cell_p] == 0:
                level = 0
                while code_p+1 < code_len:
                    if op == '[': level += 1
                    if op == ']': level -= 1
                    if level == 0:  break
                    code_p += 1
                    op = code[code_p]
        elif op == ']':
            if cell[cell_p] != 0:
                level = 0
                while code_p+1 < code_len:
                    if op == '[': level += 1
                    if op == ']': level -= 1
                    if level == 0:  break
                    code_p -= 1
                    op = code[code_p]
        code_p += 1


if __name__ == "__main__":
    sys.exit(main())