Created
March 28, 2016 13:05
-
-
Save Li-blog/ccf9335548da0574250b to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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