Skip to content

Instantly share code, notes, and snippets.

@Li-blog
Created March 28, 2016 13:05
Show Gist options
  • Save Li-blog/ccf9335548da0574250b to your computer and use it in GitHub Desktop.
Save Li-blog/ccf9335548da0574250b to your computer and use it in GitHub Desktop.
def interpret(source):
op = [0] * 255
pointer = 0
i = 0
start = []
while i < len(source):
if source[i] == '<':
pointer -= 1
elif source[i] == '>':
pointer += 1
elif source[i] == '+':
op[pointer] += 1
elif source[i] == '-':
op[pointer] -= 1
elif source[i] == '.':
sys.stdout.write(chr(op[pointer]))
elif source[i] == ',':
char = raw_input()
while len(char) != 1: # 一次只读入一个字节
char = raw_input()
op[pointer] = ord(char)
elif source[i] == '[':
start.append(i) # 存储循环开始的位置
shellCount = len(start) # 目前的循环层数
# 寻找对应的循环结束符
for j in range(len(source) - 1, i + 1, -1):
if source[j] == ']':
shellCount -= 1
if shellCount == 0:
i = j - 1 # 跳转至对应的循环结束符
break
else:
if op[pointer] != 0:
i = start[-1] # 返回对应的循环开始符的下一指令
else:
del start[-1] # 删除栈顶的循环开始符记录
i += 1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment