我有一个跟踪两个轨迹之间距离的函数,函数recMethod()是递归函数。我想将这个递归函数转换为迭代函数。
def dist(pt1,pt2):
return math.sqrt((pt2[0]-pt1[0])*(pt2[0]-pt1[0])+(pt2[1]-pt1[1])*(pt2[1]-pt1[1]))
def recMethod(ca,i,j,P,Q):
if ca[i,j] > -1:
return ca[i,j]
elif i == 0 and j == 0:
ca[i,j] = euc_dist(P[0],Q[0])
elif i > 0 and j == 0:
ca[i,j] = max(recMethod(ca,i-1,0,P,Q),euc_dist(P[i],Q[0]))
elif i == 0 and j > 0:
ca[i,j] = max(recMethod(ca,0,j-1,P,Q),euc_dist(P[0],Q[j]))
elif i > 0 and j > 0:
ca[i,j] = max(min(recMethod(ca,i-1,j,P,Q),recMethod(ca,i-1,j-1,P,Q),recMethod(ca,i,j-1,P,Q)),euc_dist(P[i],Q[j]))
else:
ca[i,j] = float("inf")
return ca[i,j]
答案 0 :(得分:1)
你只需要以正确的顺序填写表格ca,在这种情况下从0,0到len(P)-1,len(Q)-1 一种方法是:
def iterative(ca, P,Q):
ca[0,0] = euc_dist(P[0],Q[0])
for ii in range(1,len(P)):
ca[ii,0] = max(ca[ii-1,0], euc_dist(P[ii],Q[0]))
for jj in range(1,len(Q)):
ca[0,jj] = max(ca[0,jj-1], euc_dist(P[0],Q[jj]))
for ii in range(1,len(P)):
for jj in range(1,len(Q)):
ca[ii,jj] = max(min(ca[ii-1,jj],
ca[ii-1,jj-1],
ca[ii,jj-1]),
euc_dist(P[ii],Q[jj]))
return ca[-1,-1]