为什么
yield [cand]
return
导致不同的输出/行为
return [[cand]]
最小可行示例
- 使用递归
- 使用的版本的输出与使用的版本的
yield [1]; return
输出不同return [[1]]
def foo(i):
if i != 1:
yield [1]
return
yield from foo(i-1)
def bar(i):
if i != 1:
return [[1]]
yield from bar(i-1)
print(list(foo(1))) # [[1]]
print(list(bar(1))) # []
最小可行反例
- 不使用递归
- 使用的版本的输出与使用
yield [1]; return
的版本的输出相同return [[1]]
def foo():
yield [1]
return
def foofoo():
yield from foo()
def bar():
return [[1]]
def barbar():
yield from bar()
print(list(foofoo())) # [[1]]
print(list(barbar())) # [[1]]
完整的上下文
我正在解决Leetcode #39: Combination Sum并且想知道为什么一种解决方案有效,而另一种则无效:
工作解决方案
from functools import cache # requires Python 3.9+
class Solution:
def combinationSum(self, candidates: List[int], target: int) -> List[List[int]]:
@cache
def helper(targ, i=0):
if i == N or targ < (cand := candidates[i]):
return
if targ == cand:
yield [cand]
return
for comb in helper(targ - cand, i):
yield comb + [cand]
yield from helper(targ, i+1)
N = len(candidates)
candidates.sort()
yield from helper(target)
非工作解决方案
from functools import cache # requires Python 3.9+
class Solution:
def combinationSum(self, candidates: List[int], target: int) -> List[List[int]]:
@cache
def helper(targ, i=0):
if i == N or targ < (cand := candidates[i]):
return
if targ == cand:
return [[cand]]
for comb in helper(targ - cand, i):
yield comb + [cand]
yield from helper(targ, i+1)
N = len(candidates)
candidates.sort()
yield from helper(target)
输出
在以下输入
candidates = [2,3,6,7]
target = 7
print(Solution().combinationSum(candidates, target))
工作解决方案正确打印
[[3,2,2],[7]]
而非工作解决方案打印
[]
我想知道为什么yield [cand]; return
有效,但return [[cand]]
没有。