简体   繁体   中英

python: creating graph nodes from a parenthesized edges

I'm trying to create a graph from an input which looks like this:

(1 2) (2 3) (3 4) (4 1) 

the representation above is space-separated and each parenthesized argument represent a edge between two nodes. I am not sure which kind of matrix representation will be easier to use.. a matrix-adjacency or linked list adjacency ?

Any ideas about how to parse such input? and how to store it right away in the matrix for example?

Thanks in advance!

In term of ease of use, matrix-adjacency is preferable, even the edge detection between two nodes happen in O(1) time. If your network is huge and sparse, you would want to avoid wasting too much space putting zeros in matrix-adjacency, then you should use linked list adjacency. In your case, as it is a small graph, it doesn't matter much.

你可以这样解析

points = re.findall("\((\d+) (\d+)\)","(1 2) (2 3) (3 4) (4 1) ")

I would suggest building a dictionary which maps nodes to a set of nodes it is connected to. This is assuming your edges are one-way.

info = '(1 2) (2 3) (3 4) (4 1)'
info = info.replace('(','').replace(')','')
info = info.split(' ')
edges={};
for i in range(1,len(info)):
    if i%2 == 1:
        startnode = info[i-1]
        endnode = info[i]
        if startnode not in edges:
            edges[startnode] = set()
        edges[startnode].add(endnode)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM