Python3 DFS 递归
24点游戏算法
http://www.nowcoder.com/questionTerminal/fbc417f314f745b1978fc751a54ac8cb
import sys def dfs(nums): l = len(nums) if len(nums) == 1: return abs(nums[0] - 24) < eps for i in range(l): for j in range(i + 1, l): new_nums = [nums[k] for k in range(l) if i != k != j] if dfs(new_nums + [nums[i] + nums[j]]) or dfs(new_nums + [nums[i] - nums[j]]) or dfs(new_nums + [nums[j] - nums[i]])\ or dfs(new_nums + [nums[i] * nums[j]]) or (abs(nums[j]) > eps and dfs(new_nums + [nums[i] / nums[j]]))\ or (abs(nums[i]) > eps and dfs(new_nums + [nums[j] / nums[i]])): return True return False eps = 1e-6 for line in sys.stdin: nums = list(map(int, line.split())) print('true' if dfs(nums) else 'false')