Execute Brain****/Python: Difference between revisions

From Rosetta Code
Content added Content deleted
(New page: {{implementation|Brainf***}}{{collection|RCBF}}Category:Python Quick implementation of a Brainfuck interpreter in Python. <python> #!/usr/bin/python from __future__ import with_...)
 
m (Fixed syntax highlighting.)
 
(10 intermediate revisions by 8 users not shown)
Line 1: Line 1:
{{implementation|Brainf***}}{{collection|RCBF}}[[Category:Python]]
{{implementation|Brainf***}}{{collection|RCBF}}


Quick implementation of a [[Brainfuck]] interpreter in Python.
Implementation of a [[Brainfuck]] interpreter in [[Python]].

<python>
#!/usr/bin/python

from __future__ import with_statement


<syntaxhighlight lang="python">#!/usr/bin/python
import sys
import sys
import collections
#from collections import defaultdict instead since this only uses defaultdict?


def brainfuck (fd=None):
class BrainFuck():
fd = fd or (open(sys.argv[1]) if sys.argv[1:] else sys.stdin)
def __init__(self):
source = fd.read()
self.instructions = []
loop_ptrs = {}
loop_stack = []
def main(self):
if len(sys.argv[1]) > 0:
for ptr, opcode in enumerate(source):
source_file = sys.argv[1]
if opcode == '[': loop_stack.append(ptr)
if opcode == ']':
with open(source_file) as source_handle:
if not loop_stack:
self.instructions = [char for char in source_handle.read()]
else:
source = source[:ptr]
print 'No source file.'
sys.exit(2)
self.match_braces()
def match_braces(self):
loops = {}
loop_stack = {}
lsptr = 0
ptr = 0
for instruction in self.instructions:
if instruction == '[':
loop_stack[lsptr] = ptr
lsptr += 1
elif instruction == ']':
lsptr -= 1
startptr = loop_stack[lsptr]
loops[startptr] = ptr
loops[ptr] = startptr
ptr += 1
self.start_interpreting(loops)
def start_interpreting(self, loops):
tape = [0 for x in range(0, 30000)]
cell = 0
pointer = 0
while True:
if pointer > len(self.instructions) - 1:
break
break
sptr = loop_stack.pop()
instruction = self.instructions[pointer]
loop_ptrs[ptr], loop_ptrs[sptr] = sptr, ptr
if loop_stack:
raise SyntaxError ("unclosed loops at {}".format(loop_stack))
if instruction == '>':
tape = collections.defaultdict(int)
cell += 1
cell = 0
elif instruction == '<':
cell -= 1
ptr = 0
while ptr < len(source):
elif instruction == '+':
tape[cell] += 1
opcode = source[ptr]
elif instruction == '-':
if opcode == '>': cell += 1
tape[cell] -= 1
elif opcode == '<': cell -= 1
elif instruction == ',':
elif opcode == '+': tape[cell] += 1
tape[cell] = ord(sys.stdin.read(1))
elif opcode == '-': tape[cell] -= 1
elif instruction == '.':
elif opcode == ',': tape[cell] = ord(sys.stdin.read(1))
sys.stdout.write(chr(tape[cell]))
elif opcode == '.': sys.stdout.write(chr(tape[cell]))
elif instruction == '[' and tape[cell] == 0:
elif (opcode == '[' and not tape[cell]) or \
pointer = loops.get(pointer)
(opcode == ']' and tape[cell]): ptr = loop_ptrs[ptr]
ptr += 1
elif instruction == ']' and tape[cell] != 0:

pointer = loops.get(pointer)
if __name__ == "__main__": brainfuck()</syntaxhighlight>
pointer += 1
if __name__ == "__main__":
interpreter = BrainFuck()
interpreter.main()
</python>

Latest revision as of 11:53, 1 September 2022

Execute Brain****/Python is an implementation of Brainf***. Other implementations of Brainf***.
Execute Brain****/Python is part of RCBF. You may find other members of RCBF at Category:RCBF.

Implementation of a Brainfuck interpreter in Python.

#!/usr/bin/python
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()
    loop_ptrs = {}
    loop_stack = []
    for ptr, opcode in enumerate(source):
        if opcode == '[': loop_stack.append(ptr)
        if opcode == ']':
            if not loop_stack:
                source = source[:ptr]
                break
            sptr = loop_stack.pop()
            loop_ptrs[ptr], loop_ptrs[sptr] = sptr, ptr
    if loop_stack:
        raise SyntaxError ("unclosed loops at {}".format(loop_stack))
    tape = collections.defaultdict(int)
    cell = 0
    ptr = 0
    while ptr < len(source):
        opcode = source[ptr]
        if   opcode == '>': cell += 1
        elif opcode == '<': cell -= 1
        elif opcode == '+': tape[cell] += 1
        elif opcode == '-': tape[cell] -= 1
        elif opcode == ',': tape[cell] = ord(sys.stdin.read(1))
        elif opcode == '.': sys.stdout.write(chr(tape[cell]))
        elif (opcode == '[' and not tape[cell]) or \
             (opcode == ']' and tape[cell]): ptr = loop_ptrs[ptr]
        ptr += 1

if __name__ == "__main__": brainfuck()