编辑代码

def knapsack_greedy(capacity, fruits):
    # 计算单位价值并按照单位价值降序排序
    fruits.sort(key=lambda x: x["价值"] / x["重量"], reverse=True)

    total_value = 0
    remaining_capacity = capacity

    for fruit in fruits:
        if fruit["重量"] <= remaining_capacity:
            total_value += fruit["价值"]
            remaining_capacity -= fruit["重量"]
        else:
            # 选择部分水果
            total_value += (fruit["价值"] / fruit["重量"]) * remaining_capacity
            break

    return total_value

if __name__ == "__main__":
    fruits = [
        {"物品名称": "苹果", "重量": 15, "价值": 300},
        {"物品名称": "香蕉", "重量": 18, "价值": 180},
        {"物品名称": "橘子", "重量": 10, "价值": 150},
        {"物品名称": "猕猴桃", "重量": 9, "价值": 270},
    ]

    capacity = 20

    result = knapsack_greedy(capacity, fruits)
    print("贪心算法得到的最大总价值为:", result)