python - 为什么在这里使用 `any` 会导致程序挂起,但使用 `for` 循环不会?
问题描述
输入
sum_possible(2017, [4, 2, 10]) # -> False
使用any
which 导致解决方案挂起/需要很长时间
def sum_possible(amount, numbers, cache = None):
if cache is None:
cache = {}
if amount in cache:
return cache[amount]
if amount == 0:
return True
if amount < 0:
return False
cache[amount] = any([sum_possible(amount - number, numbers, cache) for number in numbers])
return cache[amount]
使用for
在合理时间内解决解决方案的循环
def sum_possible(amount, numbers, cache = None):
if cache is None:
cache = {}
if amount in cache:
return cache[amount]
if amount == 0:
return True
if amount < 0:
return False
for number in numbers:
if sum_possible(amount - number, numbers, cache):
cache[amount] = True
return True
cache[amount] = False
return False
我以为any
会短路?如果return True
遇到True
?
解决方案
any()
会短路,但你正在建立一个列表来传递给any
第一个。
cache[amount] = any([sum_possible(amount - number, numbers, cache) for number in numbers])
列表理解首先被评估 - 它很渴望:
[sum_possible(amount - number, numbers, cache) for number in numbers]
用生成器表达式替换它 - 应该可以工作(惰性评估):
cache[amount] = any(sum_possible(amount - number, numbers, cache) for number in numbers)
推荐阅读
- python - pip uninstall tensorflow 抛出 _csv.Error: line contains NUL
- reactjs - 渲染的组件然后消失(react/redux/Firebase)
- oracle - 使用游标在 Oracle SQL 中执行 2 个 for 循环
- javascript - APIRest 文件中的问题通过 node.js 中的 GET
- algorithm - 金矿问题 - for 循环的序列
- node.js - 使用 websockets 时 mocha 测试未退出,即使使用 websocket.close/terminae
- c# - 带有 CKEditor 到 Azure WebApp 的 ASP.Net MVC 应用程序给出“无法启动 CKFinder:语言文件丢失或损坏”
- c++ - FHD 视频流上 OpenCV 文本覆盖的 CPU 占用太高
- moodle - 无法在 Catalina 上安装最新版本的 moodle4mac
- algorithm - 如何使用 Dijkstra 算法找到具有顶点约束的最短路径