pythonlistsetedgesstrongly-connected-graph

How to get a list of edges in python corresponding to a set?


# inputs

edges = [ [1,2] , [2,3] , [3,4] , [4,5] , [5,2] , [4,6] , [6,7] , [7,6] , [7,8] ]

sets = [ [2,3,4,5] , [6,7] ]

# output

sets_of_edges = [ [ [2,3] , [3,4] , [4,5] , [5,2] ] , [ [6,7] , [7,6] ] ]

How do I write a code that takes 'edges' and 'sets' and outputs 'sets_of_edges', by going through each set in 'sets' and getting the sets of edges that contain both of each value in sets (if that makes sense). I have written an example input and outputs to help explain. Thanks! :)


Solution

  • Here is a quick code sample that should solve your problem:

    # inputs
    
    edges = [[1, 2], [2, 3], [3, 4], [4, 5], [
        5, 2], [4, 6], [6, 7], [7, 6], [7, 8]]
    
    sets = [[2, 3, 4, 5], [6, 7]]
    
    # output
    
    sets_of_edges = [[[2, 3], [3, 4], [4, 5], [5, 2]], [[6, 7], [7, 6]]]
    
    res = []
    for current_set in sets:
        temp = []
        for current_edge in edges:
            if current_edge[0] in current_set and current_edge[1] in current_set:
                temp.append(current_edge)
        res.append(temp)
    
    print(res)