题解 | #24点游戏算法#
24点游戏算法
https://www.nowcoder.com/practice/fbc417f314f745b1978fc751a54ac8cb
def dfs(nums): if len(nums) == 1: if abs(nums[0]-24) <= 1e-1: return True else: return False for i in range(len(nums)-1): for j in range(i+1, len(nums)): if i != j: a = nums[i] b = nums[j] ans = dfs(nums[:i] + nums[i+1:j] + nums[j+1:] + [a+b]) \ or dfs(nums[:i] + nums[i+1:j] + nums[j+1:] + [a-b]) \ or dfs(nums[:i] + nums[i+1:j] + nums[j+1:] + [a*b]) \ or (b != 0 and dfs(nums[:i] + nums[i+1:j] + nums[j+1:] + [a/b])) if ans == True: return ans return False nums = list(map(int, input().split())) if dfs(nums): print("true") else: print("false")