Common graph structure Representation (python)

Source: Internet
Author: User
python represents a common diagram structure

The structure of the diagram is shown in the following figure

1. Adjacency Set

# Assign the number of nodes to the corresponding node to facilitate the operation of
A, B, C, D, E, F, g, H = range (8)
N = [{' B ', ' C ', ' d ', ' e ', ' f '},
     {' C ', ' e '}, {'
     d '},
     {' E '},
     {' F '},
     {' C ', ' g ', ' h '}, {' F ', ' h '}
     ,
     {' F ', ' G '}]
each set in the list is a set of contiguous points of each node
in the python2.7, set ([1,3]) so expressed, Set () represents an empty collection.
in the Python3 version, set{1,3} represents the collection, and the empty collection is still represented by set ().
#查看a的邻接节点有哪些
N[a]
{' B ', ' C ', ' d ', ' e ', ' f '}
# Check whether G is an adjacency node of a
' G ' in N[a]
False
# Node A's degrees
len (N[a])
5

2. Adjacency list

# represents the same diagram
A, B, C, D, E, F, g, H = range (8)
N = [[' B ', ' C ', ' d ', ' e ', ' f '],
      [' C ', ' e '], ['
      d '],
      [' E ']],< c5/>[' F '],
      [' C ', ' g ', ' H '],
      [' f ', ' H '],
      [' f ', ' G ']]
# adjacency list representation diagram structure, same as Adjacency set operation
' G ' in N[a]
False
Len (N[a])
5

3. Adjacency Dictionary

The above two representations do not indicate the association with the neighbor node
Adjacent dictionaries, using the Dict type instead of Set () and list, representing each contiguous node with a key-value pair

A, B, C, D, E, F, g, H = range (8)
N = [{' B ']: 2, ' C ': 1, ' d ': 3, ' E ': 9, ' F ': 4},
     {' C ': 4, ' E ': 3},
     {' d ': 8},
     { ' E ': 7},
     {' F ': 5},
     {' C ': 2, ' G ': 2, ' H ': 2},
     {' F ': 1, ' H ': 6},
     {' F ': 9, ' G ': 8}]
' E ' in N[a]
True
Len (N[b])
2
# The weight of the edge
n[a][' C ']
1

Nested Dictionaries

# The above three kinds of graphs are represented by using the list type
# below using nested dictionary structure
N = {' A ': {' B ': 2, ' C ': 1, ' d ': 3, ' E ': 9, ' F ': 4}, '
     B ': {' C ': 4, ' E ': 3},
     ' C ': {' d ': 8},
     ' d ': {' E ': 7},
     ' E ': {' F ': 5},
     ' F ': {' C ': 2, ' G ': 2, ' H ': 2},
     ' G ': {' F ': 1, ' H ': 6},
     ' h ': { ' F ': 9, ' G ': 8}}
' F ' in n[' e ']
True
Len (n[' e '])
1
# a,e link weights
n[' A ' [' E ']
9
# The Dictionary of the adjacency set denotes
N = {' A ': Set (' Bcdef '),
     ' B ': Set (' CE '),
     ' C ': Set (' d '),
     ' d ': Set (' E '),
     ' E ': Set (' F ') ' ),
     ' F ': Set (' CGH '),
     ' G ': Set (' FH '),
     ' H ': Set (' FG ')}
# if the set () constructor is omitted, the key value is represented by an adjacency string, which works like an adjacency list
' H ' in n[' a ']
False
Len (n[' G '])
2

 
4. Adjacency Matrix

# adjacency Matrix, through a two-dimensional array, for each node in the graph, use 0 to indicate whether the related node is a neighbor of the current node
# You can use a nested list to implement
A, B, C, D, E, F, g, H = range (8)

N = [[0, 1,  1, 1, 1, 1, 0, 0],
     [0, 0, 1, 0, 1, 0, 0, 0], [0, 0, 0, 1
     , 0, 0, 0, 0],
     [0, 0, 0, 0, 1, 0, 0, 0],
     [0, 0, 0, 0, 0, 1, 0, 0],
     [0, 0, 1, 0, 0, 0, 1, 1-0, 0, 0, 0, 0], [1, 0, 1, 0, 0, 0, 0,
     0]]
# Check whether a, B is an adjacent node, that is, check n[a][b] is 1
n[a][b] = = 1
True
# c node's degree
sum (n[c])
1
# Extend the adjacency matrix, realize a no self circulation, the Edge weighted
# No self-cycling state, diagonal elements are all 0
# weighted, replace the value
of Truth # to set the nonexistent edge to a poor large weight (float (' inf ')), or none
A, B, C, D, E, F, g, H = range (8)
inf = float (' inf ')

N = [[  0,   2,   1,   3,   9,   4, INF, inf],
  [inf,   0,   4, INF,   3, INF, INF, INF],
     [INF, INF,   0,   8, INF, INF, INF, INF],
     [INF, INF , INF,   0,   7, INF, INF, INF, [INF, INF, INF,
     INF,   0,   5, INF, INF],
     [INF, INF,   2, INF, I NF,   0,   2,   2],
     [INF, INF, INF, INF, INF,   1,   0,   6],
     [INF, INF, INF, INF, INF,   9,   8,   0]]
# Check whether the a,b are adjacent to each other, as long as the neighboring weights are not infinity
N[a][b] < inf
True
# A node's degree
#-1 is because of the diagonal element, to remove
sum (1 for W in N[a] if w < INF)-1
5

The Python Third-party Library also provides a way to implement arrays, matrices, numpy,sicpy,scipy also supports sparse matrix implementations, and saves memory

------------------------------------------------------------------------------
the expression of a tree
# using nested lists to implement a tree with roots
# organize each subtree into a subtree list
T = [[' A ', ' B '], [' C '], [' d ', [' e ', ' F ']]]

The structure of the tree is as follows
      

T[0][1]
' B '
T[2][0]
' d '

1. Two fork Tree

Class Tree:
    def __init__ [Self, left, right]:
        Self.left = left
        Self.right = right
#创建类的实例
t = tree (' A ', ' B '), Tree (' C ', ' d '))
# access to the leaf nodes of the left subtree
t.left.right
' B '

multi-Channel search

Class Tree:
    def __init__ (self, Kids, Next=none):
        self.kids = Self.vlaue = Kids Self.next
        = Next
# property value only provides a more descriptive name for kids, rather than alias T = tree (
' A ', tree (' B ', tree (' C ', tree (' d ')
)) T.vlaue.next.next.vlaue
C
T.kids.next.next.vlaue
C

Using bunch mode to implement a tree structure

# Bunch is implemented in a variety of ways, following is one of the
class Bunch (dict):
    def __init__ (self, *args, **kwds):
        super (). __init__ (*args, * *kwds)
        self.dict = Self
# mode inherits from the dictionary class, so some operations are the same as the dictionary
Example
x = Bunch (name = ' Jinghui ', age =)
x[' name ']
' Jinghui '
# tree instance
t = Bunch t
= t (left = t (left = ' a ', right = ' B '), right = t (left = ' C ', right = t (left = ' d ', right = ' e ') )))
# Left child tree
t[' ieft ']
{' Left ': ' A ', ' right ': ' B '}
# Zuozi Left leaf node t[' ieft '
]
A
# Right subtree has left child node ' Ieft
' in t[' right-hand ']
True
t[' right ' [' right '] [' left ']
' d '
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.