编辑代码

class Fruit:
    def __init__(self, name, weight, value):
        self.name = name
        self.weight = weight
        self.value = value

    def unitPrice(self):
        return self.value / self.weight


def packFruits(backpackCapacity, fruits):
    selectedFruits = []  # 记录选择的水果

    # 1. 按照单价从高到低进行排序
    fruits.sort(key=lambda x: x.unitPrice(), reverse=True)

    # 2. 单价从高到低依次选取水果
    for fruit in fruits:
        if backpackCapacity >= fruit.weight:
            selectedFruits.append(Fruit(fruit.name, fruit.weight, fruit.value))
            backpackCapacity -= fruit.weight
        else:
            fraction = backpackCapacity / fruit.weight
            selectedFruits.append(Fruit(fruit.name, fraction * fruit.weight, fraction * fruit.value))
            break

    return selectedFruits


fruits = [
    Fruit("苹果", 15, 300),
    Fruit("香蕉", 18, 180),
    Fruit("橘子", 10, 150),
    Fruit("猕猴桃", 9, 270)
]

backpackCapacity = 20

selectedFruits = packFruits(backpackCapacity, fruits)

totalValue = 0

print("背包里面应装以下水果:")
for fruit in selectedFruits:
    totalValue += fruit.value
    print(fruit.name + " " + str(fruit.weight) + "kg")

print("总价值:" + str(totalValue) + "元")