回答此问题可获得 20 贡献值,回答如果被采纳可获得 50 分。
<p>我被布置了家庭作业来想出解决旅行推销员问题的python程序。在课堂上,他们解释了它应该如何工作,并展示了一个例子。</p>
<pre><code>path_map = [[0,10,15,20],
[5,0,9,10],
[6,13,0,12],
[8,8,9,0]]
</code></pre>
<p>这是一张示例地图
我认为这是一个流行的问题,我可以在互联网上找到解决这个问题的算法。但我不能。我试过我自己的版本。但我失败了。任何帮助都将不胜感激。
这是我目前所拥有的</p>
<pre><code>class TSP:
def __init__(self, init, path_map):
self.init = init
self.cost = 0
self.path_map = path_map
self.vertices = [i for i in range(1,len(path_map)+1)]
def min_path(self, start):
if not self.vertices:
return self.path_map[start-1][init-1]
else:
m = [i for i in range(len(self.vertices)+1)]
i=0
for v in self.vertices:
tv = self.vertices.pop(v-1)
m[i]=self.cost + self.min_path(v)
self.vertices.insert(v-1,tv)
i = i + 1
self.cost = self.cost + min(m)
return cost `
</code></pre>
<p>当我试着运行它时,我得到的是:</p>
<pre><code>>>> t = TSP(1,path_map)
>>> t.min_path(1)
Traceback (most recent call last):
File "<pyshell#54>", line 1, in <module>
t.min_path(1)
File "/home/wanhrust/python/TSP.py", line 42, in min_path
m[i]=self.cost + self.min_path(v)
File "/home/wanhrust/python/TSP.py", line 42, in min_path
m[i]=self.cost + self.min_path(v)
File "/home/wanhrust/python/TSP.py", line 42, in min_path
m[i]=self.cost + self.min_path(v)
File "/home/wanhrust/python/TSP.py", line 41, in min_path
tv = self.vertices.pop(v)
IndexError: pop index out of range
</code></pre>