【发布时间】:2014-08-26 04:06:25
【问题描述】:
我读过,python 中的递归工作非常缓慢。是否可以将此递归更改为循环函数,这样可以更快地工作? 我的功能有点复杂,但我会尽量展示最重要的部分:
class Element(object):
def __init__(self, name):
self.name = name
self.priority = randint(1000)
# some other operations and functions
import heapq
def fun(name):
if condition():
e = Element(name)
# make some operations
for i in e.sublist:
if condition2():
heapq.heappush(heap,e)
else:
updatepriority(e)
if heap:
top = heapq.heappop(heap)
fun(top.name)
所以我有一个递归函数,它搜索抛出许多子列表并使用 heapq 模块构建一个优先级队列。 如果我有一个递归函数,例如计算斐波那契数,我可以轻松地将递归转换为循环。但是在我的函数中,我没有返回语句,所以我不确定我该怎么做。
【问题讨论】:
-
heap在用于if heap:之前未定义。 -
new Element(name)也不是你在 python 中初始化类的方式。只需使用Element(name)。 -
“python 中的递归工作非常缓慢” 据我所知,在 Python 中使用递归并没有天生的慢。与内联循环相比,这是一个额外的函数调用(是否递归),它会减慢速度。还是我错了?
-
Python 没有尾调用优化,因此堆栈会增长,因此您可以获得堆栈溢出或内存不足。堆栈操作将导致它比循环慢一点。
-
@AndrewJohnson 是的,因为它是在其他函数中定义的,这里没有,所以我没有写。但我想每个人都知道
heap只是一个列表。
标签: python loops python-2.7 optimization recursion