目标是从以下内容开始:
budget = 100
projects = [('B', 60), ('A', 35), ('F', 35), ('G', 35), ('C', 20), ('E', 20), ('D', 10)]
并实现projects=[('B', 60), ('A', 35)]
和remainingBudget =5
。
作为JS程序员,我已经通过某种方式获得了以下工作:
def findProjectsThatFitTheBudget(budget, projects):
# find the most expensive projects that fit the given budget, and note the budget that remains after allocations
remainingBudget = budget
def shoulIncludeProject(name, cost):
nonlocal remainingBudget
if(cost <= remainingBudget):
remainingBudget -= cost
return True
return False
projects = list(
takewhile(lambda project: shoulIncludeProject(project[0], project[1]), projects))
# we now have the projects we are working with, and also the budget that remains unallocated
我想知道重构此问题的最pythonic方法是什么?我至少对以下内容感到困惑:
and
短路使用budget=-cost
一个不错的解决方案可能是:
projects = list(
takewhile(lambda name, cost: cost<= budget and budget=-cost, projects))
以and
的方式使用short-circuit
。
答案 0 :(得分:0)
一个简单的for
循环就没问题,该循环会在预算用尽时短路:
viable_projects = []
for project, cost in projects:
budget -= cost
if budget < 0:
break
viable_projects.append((project, cost))
viable_projects
变为:
[('B', 60), ('A', 35)]