Find path from a list of tuples in Python

前端 未结 3 486
醉话见心
醉话见心 2021-01-14 21:55

I have a list of tuples of the form:

data = [(\'Abe\', \'Bob\', \'3\'), 
        (\'Abe\', \'Frank\', \'5\'),
        (\'Abe\', \'George\', \'4\'),
        (         


        
3条回答
  •  日久生厌
    2021-01-14 22:49

    There are several packages that are already developed and debugged that do this, e.g., networkx

    import networkx as nx
    
    data = [('Abe', 'Bob', '3'), 
            ('Abe', 'Frank', '5'),
            ('Abe', 'George', '4'),
            ('Carl', 'Bob', '1'),
            ('Dan', 'Carl', '2')]
    
    g = nx.Graph()
    for e in data:
        g.add_edge(e[0], e[1], distance=int(e[2]))
    >>> nx.shortest_path(g, 'Abe', 'Bob', 'distance'), nx.shortest_path_length(g, 'Abe', 'Bob', 'distance')
    (['Abe', 'Bob'], 3)
    

提交回复
热议问题