一个Python实现24点的程序,看不懂,但是激发了学习下的兴趣
funs = [ lambda x, item: (x+item[0],
str(x)+'+('+item[1]+')'
),
lambda x, item: (x-item[0],
str(x)+'-('+item[1]+')'
),
lambda x, item: (item[0]-x,
'('+item[1]+')-'+str(x)
),
lambda x, item: (x*item[0],
str(x)+'*('+item[1]+')'
),
lambda x, item: (item[0]==0 and (0,'ZZZ')) or \
(x/item[0],
str(x)+'/('+item[1]+')'
),
lambda x, item: (x==0 and (0,'ZZZ')) or \
(item[0]/x,
'('+item[1]+')/'+str(x)
)
]
def con(num):
l = len(num)
p = list()
if l==1: return {num[0]:str(num[0])}
for i in range(l):
for f in funs:
p += map(lambda item: f(num[i],item),
con(num[:i]+num[i+1:]).items()
)
return dict(p)
print con(map(float,[1,5,6,7])).get(21.0,0)