Anonymous user
Execute Brain****/Python: Difference between revisions
Neater code, (almost) infinite tape, 'exit' opcode (']' outside of any loop).
m (moved RCBF/Python to Execute Brain****/Python) |
(Neater code, (almost) infinite tape, 'exit' opcode (']' outside of any loop).) |
||
Line 1:
{{implementation|Brainf***}}{{collection|RCBF}}
<lang python>#!/usr/bin/python
import sys▼
import collections
def brainfuck (filename=None):
fd = filename or (open(sys.argv[1]) if sys.argv[1:] else sys.stdin)
source = fd.read()
▲import sys
loop_ptrs[ptr], loop_ptrs[sptr] = sptr, ptr
if loop_stack:
raise SyntaxError ("unclosed loops at {}".format(loop_stack))
tape = collections.defaultdict(int)
opcode = source[ptr]
elif (opcode == '[' and tape[cell]) or \
(opcode == ']' and not tape[cell]): ptr = loop_ptrs[ptr]
if __name__ == "__main__": brainfuck()</lang>▼
▲ sys.exit(2)
▲ loops = {}
▲ loop_stack = []
▲ for ptr, instruction in enumerate(self.instructions):
▲ if instruction == '[':loop_stack.append(ptr)
▲ cell = 0
▲ while pointer < len(self.instructions):
▲ if instruction == '>':
▲ cell += 1
▲ cell -= 1
▲ tape[cell] += 1
▲ tape[cell] -= 1
▲ tape[cell] = ord(sys.stdin.read(1))
▲ sys.stdout.write(chr(tape[cell]))
▲ elif instruction == '[' and tape[cell] == 0:
▲ pointer = loops[pointer]
▲ elif instruction == ']' and tape[cell] != 0:
▲if __name__ == "__main__":
|