求助
求一个24点的算法。就是输入4个数,可以判断是不是可以组成24,如果可以输出运算过程。 这是别人的,会有重复。。
arr=[]
nums=input("please input 4 integer:")
num=nums.split(' ')
for i in num:
arr.append(float(i))
def perm(items, n=None):
if n is None:
n = len(items)
for i in range(len(items)):
v = items
if n == 1:
yield v
else:
rest = items[:i] + items
for p in perm(rest, n-1):
yield v + p
def F(a,b):
arr={}
for i in a:
for j in b:
va=a
vb=b
arr.update({"("+i+"+"+j+")":va+vb})
arr.update({"("+i+"-"+j+")":va-vb})
arr.update({"("+j+"-"+i+")":vb-va})
arr.update({"("+i+"*"+j+")":va*vb})
vb>0 and arr.update({"("+i+"/"+j+")":va/vb})
va>0 and arr.update({"("+j+"/"+i+")":vb/va})
return arr
for i in perm(arr):
dic=[{"a":i},{"b":i},{"c":i},{"d":i}]
alist=F(F(F(dic,dic),dic),dic)
blist=F(F(dic,dic),F(dic,dic))
for i in alist:
if alist==24.0:
print(i.replace('a',str(dic['a'])).replace('b',str(dic['b'])).replace('c',str(dic['c'])).replace('d',str(dic['d'])))
for i in blist:
if blist==24.0:
print(i.replace('a',str(dic['a'])).replace('b',str(dic['b'])).replace('c',str(dic['c'])).replace('d',str(dic['d']))) 去重请参考:
https://zhuanlan.zhihu.com/p/33998387
页:
[1]