import operator
from itertools import product,permutations
def mydiv(n,d):
return operator.truediv(n,d) if d!=0 else 999999#不能直接用除法,是因为可能除0报错了,所以要设定这个
sys=[operator.add,operator.sub,operator.mul,mydiv]
op={sy:b for sy,b in zip(sys,"+-*/")}#zip,作用是为了一一对应上
def s24(num):
for x,y,z in product(sys,repeat=3):#可以重复的排列组合,比如aaa,bbb
for a,b,c,d in permutations(num):#(主要是组合,不能重复,比如abcd,cbad)
if x(y(a,b),z(c,d))==24:
return f"({a}{op[y]}{b}){op[x]}({c}{op[z]}{d})"
elif x(y(z(a,b),c),d)==24:
return f"(({a}{op[z]}{b}){op[y]}{c}){op[x]}{d}"
elif x(y(a,z(b,c)),d)==24:
return f"({a}{op[y]}({b}{op[z]}{c})){op[x]}{d}"
elif x(a,y(b,z(c,d)))==24:
return f"{a}{op[y]}({b}{op[y]}({c}{op[z]}{d}))"
return "no answer"#这个要等全部遍历完才输出,不然一个遍历到中间输出了就停止计算了
for nums in [ [2, 2, 2, 9],
[7, 9, 2, 8],
[7, 7, 1, 2],
[10, 10, 4, 4],
[9, 9, 10, 6],
[5, 5, 1, 5],
[5, 5, 2, 10],
[4, 1, 5, 6],
[7, 3, 3, 7],
[8, 3, 8, 3]]:
print(f"s24({nums}) -> {s24(nums)}")
Python 计算24点
最新推荐文章于 2022-11-19 16:36:51 发布