Skip to content

Instantly share code, notes, and snippets.

@akahana-1
Last active August 29, 2015 13:56
Show Gist options
  • Save akahana-1/8845833 to your computer and use it in GitHub Desktop.
Save akahana-1/8845833 to your computer and use it in GitHub Desktop.
#! /usr/env/bin python
# -*- coding;utf-8 -*-
import sys
class Parser():
def __init__(self):
self.s = ""
self.ptr = 0
self.mem = [ 0 for x in range(0, 100) ]
self.blist = {}
def __del__(self):
del self;
def start(self, str):
self.s = str
self.bsearch()
self.process()
# print(self.blist)
def process(self, index = 0):
while(index < len(self.s)):
if self.s[index] == '+':
self.mem[self.ptr] += 1
if self.mem[self.ptr] > 255:
self.mem[self.ptr] = 0
index += 1
elif self.s[index] == '-':
self.mem[self.ptr] -= 1
if self.mem[self.ptr] < 0:
self.mem[self.ptr] = 255
index += 1
elif self.s[index] == '>':
self.ptr += 1 if self.ptr + 1 < len(self.mem) else 0
index += 1
elif self.s[index] == '<':
self.ptr -= 1 if self.ptr > 0 else 0
index += 1
elif self.s[index] == '[':
if self.mem[self.ptr] == 0:
index = self.blist[index] + 1
else:
index += 1
elif self.s[index] == ']':
index = self.blist[index]
elif self.s[index] == '.':
sys.stdout.write(chr(self.mem[self.ptr]))
index += 1
elif self.s[index] == ',':
try:
ch = sys.stdin.read(1)
self.mem[self.ptr] = ord(ch)
index += 1
except:
print("Illegal Input")
break
else:
index += 1
# print(index)
# if index < len(self.s):
# self.debug(index)
else:
print()
def bsearch(self):
"""
文中のカッコの位置を特定
return : bracke position list[(first, second), ...]
"""
lb = []
for index, c in enumerate(self.s):
if c == '[':
lb.append(index)
elif c == ']':
self.blist[lb[-1]] = index
self.blist[index] = lb[-1]
lb.pop(-1)
def debug(self, index):
print("Case :" + str(index))
print(self.s[index])
print(self.mem)
print(self.blist)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment