python-2.7 - 读入 TSP 文件 Python

标签 python-2.7 traveling-salesman

我需要弄清楚如何读入文件名“berlin52.tsp”的数据

这是我正在使用的格式

NAME: berlin52
TYPE: TSP
COMMENT: 52 locations in Berlin (Groetschel)
DIMENSION : 52
EDGE_WEIGHT_TYPE : EUC_2D
NODE_COORD_SECTION
1 565.0 575.0
2 25.0 185.0
3 345.0 750.0
4 945.0 685.0
5 845.0 655.0
6 880.0 660.0
7 25.0 230.0
8 525.0 1000.0
9 580.0 1175.0
10 650.0 1130.0

这是我当前的代码
# Open input file
infile = open('berlin52.tsp', 'r')

# Read instance header
Name = infile.readline().strip().split()[1] # NAME
FileType = infile.readline().strip().split()[1] # TYPE
Comment = infile.readline().strip().split()[1] # COMMENT
Dimension = infile.readline().strip().split()[1] # DIMENSION
EdgeWeightType = infile.readline().strip().split()[1] # EDGE_WEIGHT_TYPE
infile.readline()

# Read node list
nodelist = []
N = int(intDimension)
for i in range(0, int(intDimension)):
    x,y = infile.readline().strip().split()[1:]
    nodelist.append([int(x), int(y)])

# Close input file
infile.close()

代码应读入文件,输出值为“1、2、3...”等的游览列表,同时存储 x 和 y 值以计算距离。它至少可以收集标题。创建节点列表时会出现问题。

这是我得到的错误
ValueError: invalid literal for int() with base 10: '565.0'

我在这里做错了什么?

最佳答案

这是一个 TSPLIB 格式的文件。要在 python 中加载它,请查看 python 包 tsplib95 , 可通过 PyPi 获得或在 Github

文档位于 https://tsplib95.readthedocs.io/

您可以将 TSPLIB 文件转换为 networkx图形并从那里检索必要的信息。

关于python-2.7 - 读入 TSP 文件 Python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47719924/

相关文章:

python - 如何断言模拟是用特定类型而不是实例调用的?

python - 我很难在 python 中使用 mincemeat 进行 mapreduce 来计算不同文件的字数

python - 在 Pandas 中动态命名 DataFrame

python - 我怎样才能对字典中的数字列表进行平方?

artificial-intelligence - 哪种方法在 TSP 问题 : nearest neighbour or genetic algorithms? 中产生较短的游览

python - 艰难地学习 Python Ex 25 : local variable/object assignment in functions

graph - 完整有向图的 TSP

algorithm - 附加偏序的旅行商问题

python - 如何在 Python 中对 TSP 实现动态编程算法?

algorithm - 到所有节点的非循环路径