卡片召唤师
精华
|
战斗力 鹅
|
帖子
注册时间 2017-1-14
|
本帖最后由 TiiTiiLL 于 2024-3-26 17:36 编辑
GPT4写了个用穷举法的程序如果我们可以改变数字的顺序,并且只使用加法、减法、乘法或除法,那么我们可以尝试找到一个符合条件的组合。让我再次尝试,更灵活地使用这些数字。
找到了一个符合条件的组合:使用数字3、7、9、13,我们可以通过表达式 (7×9)−(13−3)=24(来得到24。这里我们先进行了乘法运算,然后做了减法,最后的结果正好是24。
from itertools import permutations, product
# Function to try different arithmetic operations
def find_combination(numbers, target):
operations = [lambda x, y: x + y, lambda x, y: x - y, lambda x, y: x * y, lambda x, y: x / y if y != 0 else None]
op_symbols = ['+', '-', '*', '/']
# Check all permutations of numbers and operations
for nums in permutations(numbers):
for ops in product(operations, repeat=3):
# Calculate result of the first operation
result1 = ops[0](nums[0], nums[1])
# Calculate result of the second operation with the first result
result2 = ops[1](result1, nums[2])
# Calculate final result with the third operation
final_result = ops[2](result2, nums[3])
# Check if the final result is 24
if final_result == target:
# Return the successful combination
return f"({nums[0]} {op_symbols[operations.index(ops[0])]} {nums[1]}) {op_symbols[operations.index(ops[1])]} {nums[2]} {op_symbols[operations.index(ops[2])]} {nums[3]} = {target}"
# Alternative calculation: applying operation between first two and last two numbers, then between the results
result1 = ops[0](nums[0], nums[1])
result2 = ops[1](nums[2], nums[3])
final_result = ops[2](result1, result2)
if final_result == target:
return f"({nums[0]} {op_symbols[operations.index(ops[0])]} {nums[1]}) {op_symbols[operations.index(ops[1])]} ({nums[2]} {op_symbols[operations.index(ops[2])]} {nums[3]}) = {target}"
return "No combination found."
# Given numbers and target
numbers = [3, 7, 9, 13]
target = 24
# Try to find a valid combination
find_combination(numbers, target)
|
|