class mNum:
def __init__(self,num):
self.num = float(num)
self.str = "%s" % num
def eval(self,second,opera):
ret = mNum(0)
if opera == "+":
ret.num = self.num + second.num
elif opera == "-":
ret.num = self.num - second.num
elif opera == "*":
ret.num = self.num * second.num
elif opera == "/":
if second.num ==0:
ret.num = 0
else:
ret.num = self.num / second.num
ret.str = "( %s %s %s )" % (str(self),opera,str(second) )
return ret
def __str__(self):
return self.str
def makeNewTuple(list_num,lpoint,rpoint,ret):
if len(list_num) == 2:
return (ret,)
nlist = list(list_num)
del nlist[lpoint]
if lpoint < rpoint:
del nlist[rpoint-1]
else:
del nlist[rpoint]
nlist.append(ret)
return tuple(nlist)
def fEval(list_num,correct):
if len(list_num) < 2:
if list_num[0].num == correct:
return str(list_num[0])
else:
return False
len_nums = len(list_num)
for lpoint in range(len_nums):
for rpoint in [e for e in range(len_nums) if e <> lpoint ]:
for opera in ("+","-","*","/"):
ret = list_num[lpoint].eval(list_num[rpoint],opera)
n_list= makeNewTuple(list_num,lpoint,rpoint,ret)
ret = fEval(n_list,correct)
if False <> ret:
return ret
return False
def Eval(nums,correct):
ret = fEval(tuple([mNum(e) for e in nums]),correct)
if False <> ret:
return "%s = %d" % (ret,correct)
return False
##测试
print Eval( ([e for e in range(10)]),24 )
搜索四则运算表达式的所有状态空间,解出一个合乎运算法则的等式