目标是从以下几点开始:
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
我想知道什么是重构这一点最python的方式?我至少被以下几点困住了:
and
和budget=-cost
一个很好的解决方案可能是:
projects = list(
takewhile(lambda name, cost: cost<= budget and budget=-cost, projects))
以short-circuit
的方式使用and
预算耗尽时短路的简单
for
循环没有问题:viable_projects
变成:相关问题 更多 >
编程相关推荐