簡體   English   中英

讀取帶有圖的邊列表的文件並在 Python 中創建鄰接列表

[英]Read a file with an edge list for a graph and create adjacency list in Python

我的程序創建了一個完整的圖,打印了邊,然后創建了一個鄰接表。 但是,效率不高。 我希望該程序:

  1. 將邊列表打印到文本文件中,然后
  2. 讓程序的創建鄰接列表部分讀取該邊緣列表文件並打印鄰接列表。 目前,我將邊緣列表硬編碼到程序中,但效率不高,因為我需要能夠更改 V 以測試不同的運行時。
import networkx as nx
import matplotlib.pyplot as plt

#Create complete graph
complete_graph = nx.complete_graph(10)
plt.subplot(121)
nx.draw(complete_graph, with_labels=True, font_weight='bold')

#list edges -----I want this to output to a file instead
list(complete_graph.edges)

# A class to represent the adjacency list of the node 
class AdjNode: 
    def __init__(self, data): 
        self.vertex = data 
        self.next = None
  
# A class to represent a graph. A graph 
# is the list of the adjacency lists. 
# Size of the array will be the no. of the 
# vertices "V" 

class Graph: 
    def __init__(self, vertices): 
        self.V = vertices 
        self.graph = [None] * self.V 
  
    # Function to add an edge in an undirected graph 
    def add_edge(self, src, dest): 
        # Adding the node to the source node 
        node = AdjNode(dest) 
        node.next = self.graph[src] 
        self.graph[src] = node 
  
        # Adding the source node to the destination as 
        # it is the undirected graph 
        node = AdjNode(src) 
        node.next = self.graph[dest] 
        self.graph[dest] = node 
  
    # Function to print the graph 
    def print_graph(self): 
        for i in range(self.V): 
            print("Adjacency list of vertex {}\n head".format(i), end="") 
            temp = self.graph[i] 
            while temp: 
                print(" -> {}".format(temp.vertex), end="") 
                temp = temp.next
            print(" \n") 
  
  
# Driver program to the above graph class. -----> instead of coding each edge, I'd like for main to 
# read the edge text file created earlier to create the Adjacency List. 
if __name__ == "__main__": 
    V = 10
    graph = Graph(V) 
    graph.add_edge(0, 1) 
    graph.add_edge(0, 2) 
    graph.add_edge(0, 3) 
    graph.add_edge(0, 4) 
    graph.add_edge(0, 5) 
    graph.add_edge(0, 6) 
    graph.add_edge(0, 7) 
    graph.add_edge(0, 8)
    graph.add_edge(0, 9)
    graph.add_edge(1, 2)
    graph.add_edge(1, 3)
    graph.add_edge(1, 4)
    graph.add_edge(1, 5)
    graph.add_edge(1, 6)
    graph.add_edge(1, 7)
    graph.add_edge(1, 8)
    graph.add_edge(1, 9)
    graph.add_edge(2, 3)
    graph.add_edge(2, 4)
    graph.add_edge(2, 5)
    graph.add_edge(2, 6)
    graph.add_edge(2, 7)
    graph.add_edge(2, 8)
    graph.add_edge(2, 9)
    graph.add_edge(3, 4)
    graph.add_edge(3, 5)
    graph.add_edge(3, 6)
    graph.add_edge(3, 7)
    graph.add_edge(3, 8)
    graph.add_edge(3, 9)
    graph.add_edge(4, 5)
    graph.add_edge(4, 6)
    graph.add_edge(4, 7)
    graph.add_edge(4, 8)
    graph.add_edge(4, 9)
    graph.add_edge(5, 6)
    graph.add_edge(5, 7)
    graph.add_edge(5, 8)
    graph.add_edge(5, 9)
    graph.add_edge(6, 7)
    graph.add_edge(6, 8)
    graph.add_edge(6, 9)
    graph.add_edge(7, 8)
    graph.add_edge(7, 9)
    graph.add_edge(8, 9)
    
    graph.print_graph() 

輸出:

Adjacency list of vertex 0
 head -> 9 -> 8 -> 7 -> 6 -> 5 -> 4 -> 3 -> 2 -> 1 

Adjacency list of vertex 1
 head -> 9 -> 8 -> 7 -> 6 -> 5 -> 4 -> 3 -> 2 -> 0 

Adjacency list of vertex 2
 head -> 9 -> 8 -> 7 -> 6 -> 5 -> 4 -> 3 -> 1 -> 0 

Adjacency list of vertex 3
 head -> 9 -> 8 -> 7 -> 6 -> 5 -> 4 -> 2 -> 1 -> 0 

Adjacency list of vertex 4
 head -> 9 -> 8 -> 7 -> 6 -> 5 -> 3 -> 2 -> 1 -> 0 

Adjacency list of vertex 5
 head -> 9 -> 8 -> 7 -> 6 -> 4 -> 3 -> 2 -> 1 -> 0 

Adjacency list of vertex 6
 head -> 9 -> 8 -> 7 -> 5 -> 4 -> 3 -> 2 -> 1 -> 0 

Adjacency list of vertex 7
 head -> 9 -> 8 -> 6 -> 5 -> 4 -> 3 -> 2 -> 1 -> 0 

Adjacency list of vertex 8
 head -> 9 -> 7 -> 6 -> 5 -> 4 -> 3 -> 2 -> 1 -> 0 

Adjacency list of vertex 9
 head -> 8 -> 7 -> 6 -> 5 -> 4 -> 3 -> 2 -> 1 -> 0 

完成您想要的最簡單方法是使用 json 對其進行序列化和反序列化。

您將在Graph擁有這樣的方法:

import json

def serialize(self) -> str:
    graph = {}
    for i in range(self.V): 
        temp = self.graph[i]
        tmp_list = []
        while temp:
            tmp_list.append(temp)
            temp = temp.next
        graph[i] = json.dumps(tmp_list).replace(",", "->")
    return json.dumps(graph, indent=4)

它將返回格式如下的字符串:

{
    "3": "[1->2->3]",
    "5": "[1->2->3]"
}

您可以將其保存到文件中或做任何您想做的事情。

對於反序列化,我們需要另一種方法:

@staticmethod
def deserialize(serialized: str) -> "Graph":
    serialized = serialized.replace("->", ",")
    graph_dict = json.loads(serialized)
    V = len(graph_dict)
    graph = Graph(V) 
    for src in graph_dict.keys():
        for dest in  graph_dict[src]:
            graph.add_edge(src, dest)
    return graph

更真實的方法是編寫自己的序列化格式,然后使用解釋器模式在反序列化中將其解析回,或者編寫語法並使用lark 進行解析。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM