Created
July 20, 2019 14:25
-
-
Save maokwen/702f007307fec88aa1ccf828bdf552b3 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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()) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment