class Graph:
def __init__(self,filename):#将地图建成一个邻接表
graph_edges=[]#边的长度
with open(filename) as fhandle:#读取文件,一行一行的读
for line in fhandle:
if line=="\n":#读取截止条件,注意必须加否则会报错
break
#将map.txt文件中的数据按空格分离并存储,*_代表这一行后面所有的元素。
edge_from,edge_to,cost,*_=line.strip().split(" ")
graph_edges.append((edge_from,edge_to,cost))#以元组的形式加入到graph_edges
#建立节点,set() 函数创建一个无序不重复元素集,
#可进行关系测试,删除重复数据,还可以计算交集、差集、并集等。
self.nodes =set()
for edge in graph_edges:
#初始化节点
#update() 方法用于修改当前集合,可以添加新的元素或集合到当前集合中,
#如果添加的元素在集合中已存在,则该元素只会出现一次,重复的会忽略。
self.nodes.update([edge[0],edge[1]])
#建立邻接表
self.adjacency_list = {node: set() for node in self.nodes}
for edge in graph_edges:
#字典中的键表示图中的节点,而键值则是以字典的形式存在里面包括几组一元组的形式储存的
#表示可达到节点以及权值
self.adjacency_list[edge[0]].add((edge[1],edge[2]))
def tsp(self, start, end):
# 初始化未遍历的点的集合
unvisited = set(self.nodes)
# 将起始点加入到已遍历的点的集合中
visited = {start}
# 初始化当前点为起始点
current = start
#初始化路径和距离为 0
path = []
distance = 0
while unvisited:
# 寻找当前点的最近的未遍历的点
next_node, next_distance = min([(node, cost) for node, cost in self.adjacency_list[current] if node not in visited], key=lambda x: x[1])
# 将最近的未遍历的点加入到已遍历的点的集合中
visited.add(next_node)
# 从未遍历的点的集合中删除最近的未遍历的点
unvisited.remove(next_node)
# 更新当前点为最近的未遍历的点
current = next_node
# 更新路径和距离
path.append(next_node)
distance += next_distance
# 如果最后一个遍历的点不是终点,添加一条从最后一个遍历的点到终点的边
if current != end:
# 寻找最后一个遍历的点到终点的最短距离
next_distance = min([cost for node, cost in self.adjacency_list[current] if node == end])
# 更新路径和距离
path.append(end)
distance += next_distance
return path, distance
graph = Graph('C:/Users/张心仪/Desktop/map.txt')
path, distance = graph.tsp('A', 'B')
print(path) # ['A', 'B', 'C', 'D']
print(distance) # 8
File "C:\Users\张心仪\Desktop\untitled34.py", line 61, in
path, distance = graph.tsp('A', 'B')
File "C:\Users\张心仪\Desktop\untitled34.py", line 47, in tsp
distance += next_distance
TypeError: unsupported operand type(s) for +=: 'int' and 'str'
怎么解决这样的报错