37,720
社区成员
发帖
与我相关
我的任务
分享
def h(s, t, a, n=1):
"""start from s, search for the nth a (the matching [ or ]) in the given direction.
"""
if n:
# n > 0, search further
change = [1,-1][r[s]==a]*(r[s]in'[]')
return h(s+t, t, a, n+change)
else:
# n = 0, found the position
return s
其中change = [1,-1][r[s]==a]*(r[s]in'[]')对应于下面你的代码中的1或-1
c=m[i];
if c=='[':o+=1
if c==']':o-=1
用if/else来写,相当于:
if r[s] not in '[]':
change = 0
else:
if r[s] == a:
change = 1
else:
change = -1
if s=='[' and a[p]==0:
变为:if 0==a[p]and'['==c:
2. 再利用python把True当作1, False当作0, 0当作False,非零的数当作True, 精简合并if语句:
if s=='>': p+=1
可以写成p+=s=='>'
等等.
3.
if cond:
x = a
else:
x = b
换成x=[a, b][cond]
或者x = cond and a or b
进一步的处理包括把"匹配括号"定义为函数, 合并p+=,p -=等.
下面的程序有I/O, 共341字符(空格, 换行符都算).
import os,sys
r=open(sys.argv[1]).read()
m=[0]*90000
p=i=0
h=lambda s,t,a,n=1:n and h(s+t,t,a,n+[1,-1][r[s]==a]*(r[s]in'[]'))or s
while i<len(r):
x=m[p];c=r[i];p+=(c=='>')-(c=='<');m[p]+=(c=='+')-(c=='-')
if'.'==c:os.write(1,chr(x))
if','==c:m[p]=ord(os.read(0,1)[0])
if x==0and'['==c:i=h(i+1,1,']')
if x*(']'==c):i=h(i-1,-1,'[')
i+=1