Execute Brain****/Python: Difference between revisions
m
Fixed syntax highlighting.
m (Categorization now in master page) |
m (Fixed syntax highlighting.) |
||
(5 intermediate revisions by 3 users not shown) | |||
Line 1:
{{implementation|Brainf***}}{{collection|RCBF}}
<
import sys▼
import collections
#from collections import defaultdict instead since this only uses defaultdict?
def brainfuck (fd=None):
fd = fd 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 not tape[cell]) or \
(opcode == ']' and tape[cell]): ptr = loop_ptrs[ptr]
if __name__ == "__main__": brainfuck()</syntaxhighlight>▼
▲ 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__":
|