编辑代码

# 豆子背包问题
def knapsack_problem(weights, values, capacity):
    n = len(weights)
    ratio = [(values[i] / weights[i], weights[i], values[i]) for i in range(n)]
    ratio.sort(reverse=True, key=lambda x: x[0])

    total_value = 0
    current_capacity = capacity
    for _, w, v in ratio:
        if current_capacity >= w:
            total_value += v
            current_capacity -= w

    return total_value

# 测试用例1
weights1 = [2, 3, 5, 7, 1, 4, 1]
values1 = [10, 5, 15, 7, 6, 18, 3]
capacity1 = 15
print("豆子背包问题测试结果:", knapsack_problem(weights1, values1, capacity1))  # 应输出:55

# 测试用例2
weights2 = [1, 2, 3, 4, 5]
values2 = [10, 5, 7, 8, 9]
capacity2 = 8
print("豆子背包问题测试结果:", knapsack_problem(weights2, values2, capacity2))  # 应输出:26