题解 | #24点游戏算法#
24点游戏算法
https://www.nowcoder.com/practice/fbc417f314f745b1978fc751a54ac8cb
import sys
arr = [int(i) for i in input().strip().split()]
def dfs(arr, path, used):
if len(path) == 4:
return check(path)
for i in range(0, len(arr)):
if used[i]:
continue
used[i] = True
path.append(arr[i])
if dfs(arr, path, used):
return True
path.pop()
used[i] = False
return False
def check(arr):
def add(a, b):
return a + b
def subtract(a, b):
return a - b
def multi(a, b):
return a * b
def divide(a, b):
return a / b
ops = {"+": add, "-": subtract, "*": multi, "/": divide}
for op, fn in ops.items():
if len(arr) == 2:
if fn(*arr) == 24:
return True
else:
if check([fn(*arr[:2]), *arr[2:]]):
return True
return False
ans = dfs(arr, [], [False] * len(arr))
print("true" if ans else "false")
#24点#

查看1道真题和解析