考虑以下代码片段(注意我使用全局,因为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
是因为内部嵌套的生成器是作为递归实现的吗?
答案 0 :(得分:5)
您正在使用L
的结果替换bar
,这是一个生成器本身。因此,您最终以递归嵌套的生成器表达式的形式将bar
传递回bar
。
这种结构最终会传递递归深度限制。