编辑代码

# 定义水果和它们的重量及价值
fruits = [
    ('苹果', 15, 300),
    ('香蕉', 18, 180),
    ('橘子', 10, 150),
    ('猕猴桃', 9, 270)
]

# 计算每种水果的单位重量价值并排序
fruits.sort(key=lambda x: x[2]/x[1], reverse=True)

# 背包承重限制
capacity = 20
# 总价值
total_value = 0
# 装入背包的水果和它们的重量
packed_fruits = []

# 贪心算法装入水果
for fruit in fruits:
    if capacity > 0:
        name, weight, value = fruit
        if weight <= capacity:
            # 如果水果的重量小于等于背包剩余容量,全部装入
            packed_fruits.append((name, weight))
            capacity -= weight
            total_value += value
        else:
            # 如果水果的重量大于背包剩余容量,装入部分
            fraction = capacity / weight
            packed_fruits.append((name, weight * fraction))
            total_value += value * fraction
            capacity = 0  # 背包已满

# 打印结果
print(f'装入背包的水果和它们的重量: {packed_fruits}')
print(f'背包中水果的总价值: {total_value}')