【发布时间】: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