defcompute(x,y,op):if op=='+':return x+yelif op=='*':return x*yelif op=='-':return x-yelse:return x/y if y elseNonedefexp(p,iter=0):from itertools import permutationsif len(p)==1:return [(p[0],str(p[0]))]operation = ['+','-','*','/']ret = []p = permutations(p) if iter==0else [p]for array_n in p:#print(array_n)for num in range(1,len(array_n)):ret1 = exp(array_n[:num],iter+1)ret2 = exp(array_n[num:],iter+1)for op in operation:for va1,expression in ret1:if va1==None:continuefor va2,expression2 in ret2:if va2==None:continuecombined_exp = '{}{}'if expression.isalnum() else'({}){}'combined_exp += '{}'if expression2.isalnum() else'({})'new_val = compute(va1,va2,op)ret.append((new_val,combined_exp.format(expression,op,expression2)))if iter==0and new_val==24:return''.join(e+'\n'for x,e in ret if x==24)return ret print(exp([2,3,4,11,1,3]))
做的一点优化:记忆式搜索
EXP = {} defexp(array_n,target,iter=0):if len(array_n)==1:return [(array_n[0],str(array_n[0]))]operation = ['+','-','*','/']ret = []for num in range(1,len(array_n)):exp1 = array_n[:num]exp2 = array_n[num:]ret1 = EXP[exp1] if exp1 in EXP else exp(exp1,target,iter+1)ret2 = EXP[exp2] if exp2 in EXP else exp(exp2,target,iter+1)EXP[exp1] = ret1EXP[exp2] = ret2for op in operation:for va1,expression in ret1:if va1==None:continuefor va2,expression2 in ret2:if va2==None:continuecombined_exp = '{}{}'if expression.isalnum() else'({}){}'combined_exp += '{}'if expression2.isalnum() else'({})'new_val = compute(va1,va2,op)ret.append((new_val,combined_exp.format(expression,op,expression2)))if iter==0and new_val==target:#print('ans')return''.join(e for x,e in ret if x==target)return ret if iter elseNone defsearch(array):record = set()from itertools import permutationsfor p in permutations(array):if p in record:continuerecord.add(p)ret = exp(tuple(p),100)if ret:print(ret);break