john pfeiffer
  • Home
  • Categories
  • Tags
  • Archives

graph

# 2013-04-29 johnpfeiffer

class Graph:
    """ directed edges graph
        adjacency = {  a: [ (b,1) , (c,2) ], b: [ (c,1) ] }
        a_1_b _
        \_2_c _|1
    """

    def __init__( self ):
        self._adjacency_list = dict()


    def add_edge( self , source_vertex_key, destination_vertex_key, weight=1 ):
        self._insert( source_vertex_key, destination_vertex_key, weight )

        destination = self._adjacency_list.get( destination_vertex_key )
        if not destination:
            destination = list()
        self._adjacency_list[ destination_vertex_key ] = destination
        return


    def _insert( self, vertex_key, destination_key, weight=1 ):
        vertex = self._adjacency_list.get( vertex_key )
        if not vertex:
            vertex = list()
        vertex.append( (destination_key, weight) )
        self._adjacency_list[ vertex_key ] = vertex



if __name__ == '__main__':
    graph = Graph()
    assert {} == graph._adjacency_list
    print graph._adjacency_list

    graph.add_edge( 'a', 'b' )
    print graph._adjacency_list

    graph.add_edge( 'a', 'c', 2 )
    print graph._adjacency_list

  • « find remove remove all tests
  • server chat example »

Published

Apr 29, 2013

Category

python

~83 words

Tags

  • graph 1
  • python 180