Python 3.x 我曾经尝试过解决这个问题,遇到了一个最大递归深度超过的错误
我有点傻,请对我宽容点 我正在努力解决这个问题 我正在使用的 所以我用大量的输入编写了代码,每次调用函数时它都会不断堆积起来 我想了解如何处理这个问题,而不是获得Python 3.x 我曾经尝试过解决这个问题,遇到了一个最大递归深度超过的错误,python-3.x,recursion,Python 3.x,Recursion,我有点傻,请对我宽容点 我正在努力解决这个问题 我正在使用的 所以我用大量的输入编写了代码,每次调用函数时它都会不断堆积起来 我想了解如何处理这个问题,而不是获得最大递归深度超出错误 count = 0 #a #I assign the whole input here def count_bag(x): #a #I assign the whole input here again for x in a: if x == "other ba
最大递归深度超出错误
count = 0
#a #I assign the whole input here
def count_bag(x):
#a #I assign the whole input here again
for x in a:
if x == "other bags":
continue
elif "shiny gold" in a[x]:
global count
count += 1
break
else:
for y in a[x]:
count_bag(y)
count_bag(a)
print(count)
在python中,大多数编译器的递归深度都是有限的,因此如果您想进行一些深度递归,可以使用
sys.setrecursionlimit(some value)
来解决这个问题
import sys
sys.setrecursionlimit(10**6)
在python中,大多数编译器的递归深度都是有限的,因此如果您想进行一些深度递归,可以使用
sys.setrecursionlimit(some value)
来解决这个问题
import sys
sys.setrecursionlimit(10**6)
为什么不使用队列并跳过递归呢?这样,您甚至不需要使用全局计数变量。我没有编译/整理过这个或其他东西,但类似的东西:
def count_bag(x, a):
count = 0
to_process = list()
to_process.extend(x)
while len(to_process) > 0:
item = to_process.pop(0) # pop item off front of list
if item == 'other bags':
continue
elif 'shiny gold' in a[item]:
count += 1
else:
for y in a[item]:
to_process.extend(y)
return count
为什么不使用队列并跳过递归呢?这样,您甚至不需要使用全局计数变量。我没有编译/整理过这个或其他东西,但类似的东西:
def count_bag(x, a):
count = 0
to_process = list()
to_process.extend(x)
while len(to_process) > 0:
item = to_process.pop(0) # pop item off front of list
if item == 'other bags':
continue
elif 'shiny gold' in a[item]:
count += 1
else:
for y in a[item]:
to_process.extend(y)
return count
实际上,我的输入是一本字典,正如您在这里提到的
a
,但是调用函数时,x
会是什么呢?嘿@djashkin987谢谢您的提示。我有了一个新的视角。实际上,我的输入是一本字典,正如你在这里提到的a
,但是调用函数时,x
会是什么呢?嘿@djasskin987谢谢你的提示。我有了一个新的视角。不幸的是,在使用这个视角时,python shell会自动重新启动。您使用的是什么ide,您可以在联机ide中看到结果。我使用的是python安装附带的内置IDLE。不幸的是,在使用这个视角时,python shell会自动重新启动。您使用的是什么ide,您可以在联机ide中看到结果,我正在使用python安装附带的内置IDLE。