提前致谢。
因此,我正在尝试用Python制作一个递归的旅行推销员解决方案,因为我需要从最短的路径开始#39; a'指出' b',我想要一个针对任何数量的城镇的一般解决方案。在a和b之间。
我的问题是因为我希望两个变量相同,但由于范围界定它们不是。虽然我知道具有不同范围意味着什么,但我并不熟悉范围界定的工作方式。
实际代码相当长且相互关联,所以这里是简化版本(我已经完全忽略了我为'路径',' cure_dist'以及其他一些内容找到的值变量):
def tsp_recursive(count, minim, path): # line 1
if count == 0:
path = [1, 2, 3, 4] # there is code to evaluate path; line 3
curr_dist = 0 # there is code to evaluate curr_dist
if curr_dist < minim: # this is an unimportant statement; line 5
minim = curr_dist # line 6. minim should be the same as on lines 1, 5 and 11
path = ["Some other list"] # line 7. path should be the same as on lines 1, 3 and 11
return
else:
for i in range(5):
tsp_recursive(count - 1, minim, path) # line 11
问题是第1,3,5,6,7和11行的minim和path变量应该都是相同的,但我的PyCharm说没有使用&#39;局部变量&#39;在第6和第7行
非常感谢你。
(如果需要,这里是完整的代码)
def dist_adder(array, indexes):
total = 0
for i in range(len(indexes)-1):
total += array[indexes[i]][indexes[i+1]]
return total
def tsp_recursive(count, distances, start, finish, indexes, minim, path):
"""
:param count: int | number of times to for-loop, this is len(distances-2)
:param distances: [[]] | list of lists of distances from a to b, i.e:
distances = [[-1, 3, 5, 40],
[3, -1, 2, 6],
[5, 2, -1, 1],
[40, 6, 1, -1]]
:param start: int | index of the starting point in distances
:param finish: int | index of the finishing point in distances
:param indexes: [] | list of the indexes of all the for loops; len(indexes) == len(distances) and for i in indexes: i = -1 at start
:param minim: int | the minimum path length, starts out at 'infinity'
:param path: list | a list of the shortest path, in order, by the number of the different points
:return:
"""
assert isinstance(count, int)
assert isinstance(distances, list)
assert isinstance(indexes, list)
if count == 0:
path = [start, finish]
path[1:1] = indexes
curr_dist = dist_adder(distances, path)
if curr_dist < minim:
minim = curr_dist # this line
path = indexes.copy() # and this line are where the problem is
return
else:
for i in range(len(distances)):
if i not in indexes and i != start and i != finish:
indexes[len(indexes) - count] = i
tsp_recursive(count - 1, distances, start, finish, indexes, minim, path)