gpt4 book ai didi

python - 将文本文件转换为图形

转载 作者:太空宇宙 更新时间:2023-11-03 14:39:23 25 4
gpt4 key购买 nike

我目前正在尝试解决欧拉项目中的问题 81。如何将包含数字流的 txt 文件转换为存储图形的字典?

enter image description here

现在,我的计划是使用逗号分隔的数字文本文件(它们不是“预网格”,所以它不是 80 x 80 结构)并将它们转换成一个字典,我可以将它们存储为图

所有顶点都垂直和水平连接

所以拿 txt 文件中的项目(使用 4 x 4 网格作为演示):

"a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p"

将它们转换为存储图的字典

graph = {
a: b, e
b: a, c, f
c: b, d, g
etc etc ...
}

我将使用 djkstra 算法从中找到最小路径,因为 txt 文件中的值实际上是整数并具有权重值

附言这是解决问题的好方法吗?

最佳答案

在第 81 题中,您只能向右或向下移动。因此,您的 Dijkstra 算法需要一个有向图。如果您将字典用作图形,则此字典中的每个值(列表)必须具有不超过 2 个节点(您只能在 2 个方向上移动 -> 2 个邻居)。您可以在@AustinHastings 的最后一段代码中删除前两个if block 。否则你将向 4 个方向移动并得到不同的结果。这是问题 81 中示例的解决方案。我使用了包 networkxjupyter notebook:

import networkx as nx
import numpy as np
import collections

a = np.matrix("""131 673 234 103 18;
201 96 342 965 150;
630 803 746 422 111;
537 699 497 121 956;
805 732 524 37 331""")

rows, columns = a.shape

# Part of @AustinHastings solution
graph = collections.defaultdict(list)
for r in range(rows):
for c in range(columns):
if c < columns - 1:
# get the right neighbor
graph[(r, c)].append((r, c+1))
if r < rows - 1:
# get the bottom neighbor
graph[(r, c)].append((r+1, c))

G = nx.from_dict_of_lists(graph, create_using=nx.DiGraph)

weights = {(row, col): {'weight': num} for row, r in enumerate(a.tolist()) for col, num in enumerate(r)}
nx.set_node_attributes(G, values=weights)

def weight(u, v, d):
return G.nodes[u].get('weight')/2 + G.nodes[v].get('weight')/2

target = tuple(i - 1 for i in a.shape)
path = nx.dijkstra_path(G, source=(0, 0), target=target, weight=weight)
print('Path: ', [a.item(i) for i in path])

%matplotlib inline
color_map = ['green' if n in path else 'red' for n in G.nodes()]
labels = nx.get_node_attributes(G, 'weight')
pos = {(r, c): (c, -r) for r, c in G.nodes()}
nx.draw(G, pos=pos, with_labels=True, node_size=1500, labels = labels, node_color=color_map)

输出:

Path:  [131, 201, 96, 342, 746, 422, 121, 37, 331]

enter image description here

关于python - 将文本文件转换为图形,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54587274/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com