在循环中使用递归函数python中输入参数时不记忆
我具有递归功能:
def recursive_func(parameter1):
.....
if __name__ == "__main__":
list_parameter_input = [a,b,c,d,e]
for item in list_parameter_input:
recursive_func(item)
注释:我的recursive_func
非常复杂,但我敢肯定它不会有任何错误。
问题是当我输入parameter1
用list_parameter_input
中的一个项目输入时,它很快并且需要小内存。当我输入parameter1
使用for loop时,它延长了,并使以。这很奇怪。
当recursive_func
与list> list_parameter_input
中的每个值一起检查时,我会检查时间。
输入不使用进行循环
:recursive_func(a)
需要x
时间。
输入使用for loop
:recursive_func(a)
需要更多x
time(10x
,11x
,...)但是使用b,c,d,e
给出相同的时间。
我不知道为什么会发生这种情况,但是我真的很确定recursive_func(a)
在我输入a
的情况下很快,而不使用for loop
>
I have a recursive function:
def recursive_func(parameter1):
.....
if __name__ == "__main__":
list_parameter_input = [a,b,c,d,e]
for item in list_parameter_input:
recursive_func(item)
Note: my recursive_func
is very complex but I'm sure it won't have any error.
The problem is when I input a parameter1
with a single item in list_parameter_input
, it's fast and needs small memory. When I input a parameter1
using for loop, it's prolonged and makes out of memory
.It's so weird.
I'm checked time when recursive_func
complete with each value in list_parameter_input
.
When input with not using for loop
: recursive_func(a)
need x
time.
When input with using for loop
: recursive_func(a)
need more x
time (10x
,11x
,...) but with b,c,d,e
give a same time.
I don't know why it's happen but I'm really sure recursive_func(a)
is very fast when I input a
with not using for loop
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我的意思是
recursive_func(i)
可能是recursive_func(item)
,因为您从未在任何地方使用I。但是真正的问题似乎是您正在为每次递归运行整个循环。因此,列表的每个元素都会启动递归,其中它可以通过整个列表进行循环,而不仅仅是列表的其余部分,而是整个列表。该循环的每个元素都相同,因此:
5
列表中元素的递归5*5*5*5*5*5*5*5*5*5*5*5*5*5*5*5*5*5*5*5*5*5*5*5*
。 > 5*5*5*5 递归递归列表中元素的递归
...
这很快导致堆栈溢出。
I mean
recursive_func(i)
is probablyrecursive_func(item)
as you're never using i anywhere.But the real problem seems to be that you're running the entire loop for each recursion. So each element of the list starts a recursion where it loops through the entire list, not just the rest of the list but the entire list. And each of the element of that loop does the same so:
5
recursions for the elements in the list5*5
recursions for the elements in the list in the recursions5*5*5
recursions for the elements in the list in the recursions of the recursion...
That soon leads to a stack overflow.
也许我误解了您对代码的描述(从技术上讲,您没有提供
...然后您有一个无限的循环。
即,除非修改
list_parameter_input
(删除项目),否则您不会取得进展。您可以验证您实际上正在通过输入参数取得进展吗?
Maybe I misunderstand your description of the code (you are technically not providing a Minimal, Reproducible Example), but if the code looks like this:
... then you have an infinite loop.
I.e. Unless the
list_parameter_input
is modified (items are removed) you are not making progress.Can you verify that you are actually making progress through the input parameters?