python_凑数
假设数量是x,y,z,且只能是整数,单价分别是4,5,6,目标是10,如果4X+5y+6z=10,求想,x,y,z分别是多少
def find_solutions(prices, target, index=0, current_sum=0, current_solution=[]):
if current_sum == target and index == len(prices):
yield tuple(current_solution)
elif index < len(prices):
for value in range(0, 3): # 变量取值范围
new_sum = current_sum + (prices[index] * value)
if new_sum <= target:
yield from find_solutions(prices, target, index + 1, new_sum, current_solution + [value])
def solve_combination(prices, target):
solutions = list(find_solutions(prices, target))
return solutions if solutions else "No solution"
# 定义单价和目标金额
prices = [4,5,6]
target = 10
# 调用函数并打印结果
result = solve_combination(prices, target)
print(result)
结果:
[(0, 2, 0), (1, 0, 1)]