Graph and Tree in Python

Adjacency Lists and the Like

One of the most intuitive ways of implementing graphs is using adjacency lists. Basically, for each node, we can access a list (or set or other container or iterable) of its neighbors.

a, b, c, d, e, f, g, h = range(8) 
N = [ 
{b, c, d, e, f}, # a 
{c, e},          # b 
{d},             # c 
{e},             # d 
{f},             # e 
{c, g, h},       # f 
{f, h},          # g 
{f, g}           # h 
]

In our code, N[v] is now a set of v's neighbors.

b in N[a] #neighborhood membership

len(N[f]) #Degree

Adjacency dicts with Edge Weights

a, b, c, d, e, f, g, h = range(8) 
N = [ 
{b:2, c:1, d:3, e:9, f:4}, # a 
{c:4, e:3}, # b 
{d:8}, # c 
{e:7}, # d 
{f:5}, # e 
{c:2, g:2, h:2}, # f 
{f:1, h:6}, # g 
{f:9, g:8} # h 
]

neighborhood membership

b in N[a]

Degree

#degree
len(N[f])

Edge weight

N[a][b] #Edge weight for (a,b)

 A Dict with adjacency sets

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') 
}

An adjacency matrix, implemented with Nested Lists.

a, b, c, d, e, f, g, h = range(8) 
# a b c d e f g h 
N = [[0,1,1,1,1,1,0,0], # a 
    [0,0,1,0,1,0,0,0], # b 
    [0,0,0,1,0,0,0,0], # c 
    [0,0,0,0,1,0,0,0], # d 
    [0,0,0,0,0,1,0,0], # e 
    [0,0,1,0,0,0,1,1], # f 
    [0,0,0,0,0,1,0,1], # g 
    [0,0,0,0,0,1,1,0]] # h

neighborhood membership and degree

N[a][b]

sum(N[f])

Implementing Trees

It is easiest to specialize the representation of rooted trees, where each edge is pointed downward.

T = [["a","b"],["c"],["d",["e","f"]]]

T[0][1]

T[2][1][0]

Binary tree

class Tree:
    def __init__(self,left,right):
         self.right = right
         self.left = left

 

 

 

 

posted on 2012-08-15 14:14  grep  阅读(326)  评论(0编辑  收藏  举报