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}')