考虑以下代码片段(请注意,我使用的是 global,因为非本地关键字在 Python 2.7 中不可用)
def foo(L,K):
global count
count = 0
def bar(f,L):
global count
for e in L:
if e - f == K or f - e == K: count += 1
yield e
try:
while True:
L = bar(L.next(),L)
except StopIteration:
return count
count=0
print foo((int(e) for e in some_string.split()),some_number)
在哪里
some_string: A space delimited integers
some_number: An integer
当 len(some_string) = 4000
时,上述代码因错误而失败
RuntimeError: maximum recursion depth exceeded while calling a Python object
是不是因为内部嵌套的生成器是递归实现的?
最佳答案
您正在用 bar
的结果替换 L
,它本身就是一个生成器。因此,您最终以递归嵌套生成器表达式的形式将 bar
传递回 bar
。
这个构造最终通过了递归深度限制。
关于python - 生成器表达式因最大递归深度而失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11817949/