我在将返回的解决方案正确装箱为 min_cals <= sum(calories) <= max_cals 时遇到一些困难。有一些组合可以产生 sum(cals) < min_cals 的解决方案。除了保持在热量范围内之外,解决方案还应该生成一个列表,其中总成本尽可能接近预算而不超过预算限制。这是一些重新上下文化的代码。我真的可以帮忙:
menu = [
{'name':'Cheese Pizza Slice', 'calories': 700, 'cost': 4},
{'name':'House Salad', 'calories': 100, 'cost': 8.5},
{'name':'Grilled Shrimp', 'calories': 400, 'cost': 15},
{'name':'Beef Brisket', 'calories': 400, 'cost': 12},
{'name':'Soda', 'calories': 100, 'cost': 1},
{'name':'Cake', 'calories': 300, 'cost': 3},
]
def menu_recommendation(menu, min_cal, max_cal, budget):
menu = [item for item in menu if item['calories'] <= max_cal and item['cost'] <= budget]
if len(menu) == 0: return []
return min((
[item] + menu_recommendation(menu, min_cal - item['calories'], max_cal - item['calories'], budget - item['cost'])
for item in menu
), key=
lambda recommendations: [budget - sum(item['cost'] for item in recommendations) and min_cal <= sum(item['calories'] for item in recommendations) <= max_cal, -sum(item['calories'] for item in recommendations)]
)
recommendation = menu_recommendation(menu, 1000, 1200, 15)
total_cost = sum(item['cost'] for item in recommendation)
total_cals = sum(item['calories'] for item in recommendation)
print(f'recommendation: {recommendation}')
print(f'total cost: {total_cost}')
print(f'total calories: {total_cals}')
例如,以下命令返回总卡路里数为 700 的解决方案,低于最小值 1000。推荐 = menu_recommendation(菜单, 1000, 1200, 15)
慕工程0101907
ibeautiful
GCT1015
烙印99
相关分类