python_0">计算24点的python代码
GPT-4o 确实不错,以后3.5和4.0都难以一次性解决的问题,4.0都要对话许多次才能完美实现,现在4o一次就解决了,记录一下。
import itertools
import operator# Define the basic operations
ops = {'+': operator.add,'-': operator.sub,'*': operator.mul,'/': operator.truediv
}def check24(nums):# Generate all permutations of the numbersfor num_permutation in itertools.permutations(nums):# Generate all possible operationsfor op1, op2, op3 in itertools.product(ops, repeat=3):# Apply the operations in different orders with different parenthesistry:if abs(ops[op3](ops[op2](ops[op1](num_permutation[0], num_permutation[1]), num_permutation[2]), num_permutation[3]) - 24) < 1e-6:return f"({num_permutation[0]} {op1} {num_permutation[1]}) {op2} {num_permutation[2]} {op3} {num_permutation[3]}"if abs(ops[op3](ops[op1](num_permutation[0], ops[op2](num_permutation[1], num_permutation[2])), num_permutation[3]) - 24) < 1e-6:return f"({num_permutation[0]} {op1} ({num_permutation[1]} {op2} {num_permutation[2]})) {op3} {num_permutation[3]}"if abs(ops[op1](num_permutation[0], ops[op3](ops[op2](num_permutation[1], num_permutation[2]), num_permutation[3])) - 24) < 1e-6:return f"{num_permutation[0]} {op1} (({num_permutation[1]} {op2} {num_permutation[2]}) {op3} {num_permutation[3]})"if abs(ops[op1](num_permutation[0], ops[op2](num_permutation[1], ops[op3](num_permutation[2], num_permutation[3]))) - 24) < 1e-6:return f"{num_permutation[0]} {op1} ({num_permutation[1]} {op2} ({num_permutation[2]} {op3} {num_permutation[3]}))"if abs(ops[op2](ops[op1](num_permutation[0], num_permutation[1]), ops[op3](num_permutation[2], num_permutation[3])) - 24) < 1e-6:return f"({num_permutation[0]} {op1} {num_permutation[1]}) {op2} ({num_permutation[2]} {op3} {num_permutation[3]})"except ZeroDivisionError:continuereturn "No solution found"# Example usage
numbers = [3, 3, 8, 8]
result = check24(numbers)
print(result) # Output: (8 / (3 - (8 / 3)))