import operator
from itertools
import product
,permutations
def mydiv(n
,d
):
return operator
.truediv
(n
,d
) if d
!=0 else 999999
sys
=[operator
.add
,operator
.sub
,operator
.mul
,mydiv
]
op
={sy
:b
for sy
,b
in zip(sys
,"+-*/")}
def s24(num
):
for x
,y
,z
in product
(sys
,repeat
=3):
for a
,b
,c
,d
in permutations
(num
):
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)}")
转载请注明原文地址: https://lol.8miu.com/read-10617.html