版本:Python 3.10.4
依赖
from functools import reduce from itertools import permutations
主要代码(为了美观,将代码进行了回车,去掉换行后就是一行)
def check(a: int, b: int, c: int, d: int) -> list[str]:
return reduce(lambda x, y: x+y, [
[
i for i in filter(
lambda x:eval(x) == 24,
[
f'(({way[0]} {x} {way[1]}) {y} {way[2]}) {z} {way[3]}'
for x in ['+', '-', '*', '/']
for y in ['+', '-', '*', '/']
for z in ['+', '-', '*', '/']
]
)
]
for way in set(permutations([a, b, c, d], 4))
])
使用样例
if __name__ == '__main__':
print('n'.join(check(1, 2, 3, 4)))
输出结果
((2 + 3) + 1) * 4 ((2 * 3) * 1) * 4 ((2 * 3) / 1) * 4 ((1 + 2) + 3) * 4 ((1 * 2) * 3) * 4 ((1 * 2) * 4) * 3 ((3 + 1) + 2) * 4 ((3 * 1) * 2) * 4 ((3 / 1) * 2) * 4 ((2 * 4) * 3) * 1 ((2 * 4) * 3) / 1 ((4 * 3) * 2) * 1 ((4 * 3) * 2) / 1 ((4 * 1) * 3) * 2 ((4 / 1) * 3) * 2 ((1 * 4) * 2) * 3 ((4 * 2) * 1) * 3 ((4 * 2) / 1) * 3 ((2 * 4) * 1) * 3 ((2 * 4) / 1) * 3 ((4 * 3) * 1) * 2 ((4 * 3) / 1) * 2 ((3 * 4) * 2) * 1 ((3 * 4) * 2) / 1 ((3 * 2) * 4) * 1 ((3 * 2) * 4) / 1 ((2 * 1) * 4) * 3 ((2 / 1) * 4) * 3 ((4 * 1) * 2) * 3 ((4 / 1) * 2) * 3 ((2 + 1) + 3) * 4 ((2 * 1) * 3) * 4 ((2 / 1) * 3) * 4 ((3 * 4) * 1) * 2 ((3 * 4) / 1) * 2 ((1 * 3) * 4) * 2 ((3 + 2) + 1) * 4 ((3 * 2) * 1) * 4 ((3 * 2) / 1) * 4 ((2 * 3) * 4) * 1 ((2 * 3) * 4) / 1 ((1 + 3) + 2) * 4 ((1 * 3) * 2) * 4 ((4 * 2) * 3) * 1 ((4 * 2) * 3) / 1 ((1 * 4) * 3) * 2 ((3 * 1) * 4) * 2 ((3 / 1) * 4) * 2



