我正在从事一项动态编程任务,即沿着有向图查找最小成本路径(所有可能的路径都具有相同数量的加权节点)。
解决问题的方法是递归函数和动态规划。
由于在代码过程中会遇到许多不相关的问题,因此线程的概念可能会有所帮助。
问题是,在 python 中,“线程”没有多大帮助。在 python 中处理此类任务的有效方法是什么?
这是代码:
def rec_fun(pos, path_size, weights, directions):
cost = weights[d][i, j]
if path_size == 0:
key = str(i) + ',' + str(j) + ',' + str(d)
dict.update({key: pix_cost})
return cost
else:
key = str(i) + ',' + str(j) + ',' + str(d)
if key in dict:
return dict[key]
else:
val = cost + min(rec_fun(pos + direction[0], path_size - 1, weights, direction),
rec_fun(pos + direction[1], path_size - 1, weights, direction),
rec_fun(pos + direction[2], path_size - 1, weights, direction))
dict.update({key: val})
return val