Find path from a list of tuples in Python

前端 未结 3 483
醉话见心
醉话见心 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:35

    def get_rpath_with_weight(data,start,end):
        rpath = []
        reachable=False
        nxt_dst = start
        weight_ = 0
        rpath.append(nxt_dst)
        for datum in data:
            if nxt_dst in datum:
                #print datum
                fm_ = datum[0]
                to_ = datum[1]
                weight_ = weight_ + int(datum[2])
                if fm_ == nxt_dst:
                   nxt_dst = to_
                else:
                   nxt_dst = fm_
                if nxt_dst == end:
                   reachable=True
                rpath.append(nxt_dst)
        print rpath,weight_,reachable
    
    
    get_rpath_with_weight(data,'Abe','Dan')
    
    get_rpath_with_weight(data,'Dan','Frank')
    

    Sample Output

    ['Abe', 'Bob', 'Carl', 'Dan'] 6 True
    ['Dan', 'Carl'] 2 False
    

    Above example can may get path and determine if reachable, but I think you need to further enhance it to handle multiple paths too.

提交回复
热议问题