【问题标题】:Speed up recursive method by converting into iterative通过转换为迭代来加速递归方法
【发布时间】:2018-05-23 02:18:51
【问题描述】:

我正在Python 中编写一个动态编程算法,该算法似乎对于较小的输入非常有效,但对于较大的输入它会超时,这可能是因为递归调用。我在网上读到了这个article,它说大多数现代编程语言都不能很好地处理递归,最好将它们转换为迭代方法。

我的算法如下:

def get_val(x,y,g,i,xlast,ylast):
    # checks if array over
    if(i>(len(x)-1)):
        return 0
    # else returns the max of the two values
    # dist returns the euclidian distance between the two points
    # the max condition just decides if it's profitable to move to the 
    # next x and y coordinate or if it would be better to skip this particular (x, y)
    return max(g[i]-dist(x[i],y[i],xlast,ylast) + get_val(x,y,g,i+1,x[i],y[i]),get_val(x,y,g,i+1,xlast,ylast))

我一直在努力提高它的性能,但我不确定我应该采取哪些步骤来确保它不会因大量输入而超时。

【问题讨论】:

  • 能否提供输入和预期输出,比如一个小例子
  • 你的函数做什么
  • 我更新了问题以添加更多信息

标签: python algorithm recursion iteration dynamic-programming


【解决方案1】:

编写动态编程算法意味着您已经在处理递归调用,因此您当前的代码还不是动态编程。

您需要确定导致问题的原因,然后提供一种解决方案,以减少计算函数的步骤以换取内存消耗,即存储函数调用结果以避免对同一调用进行新的计算。

我不知道你的问题的所有细节,但它似乎有一个optimal substructure property

你会找到一个指南,告诉你如何判断你正在处理什么样的问题以及如何解决它here

【讨论】:

  • 是的,我确信它确实具有最佳的子结构属性。我将检查该链接并为其创建一个子结构,谢谢
【解决方案2】:

如果我知道您想要完成什么,您可以使用生成器进行下一步。查看这些生成器技巧:

http://linuxgazette.net/100/pramode.html

或访问

https://wiki.python.org/moin/Generators

【讨论】:

    猜你喜欢
    • 2021-08-09
    • 2015-01-08
    • 1970-01-01
    • 1970-01-01
    • 2016-06-29
    • 2016-01-26
    • 2017-03-05
    相关资源
    最近更新 更多