【发布时间】:2019-05-18 11:02:09
【问题描述】:
目标是从以下开始:
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 的重构方式是什么?我至少坚持以下几点:
- 如何编写简单的 lambda 而不是外部定义
- 如何对 lambda 的参数进行解构
- 如何以短路方式使用
and与budget=-cost
一个漂亮的解决方案可能是:
projects = list(
takewhile(lambda name, cost: cost<= budget and budget=-cost, projects))
以short-circuit 的方式使用and。
【问题讨论】:
标签: python python-3.x lambda destructuring short-circuiting