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

78 views Asked by At
# 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! :)

2

There are 2 answers

0
LupaDevStudio On BEST ANSWER

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)
0
blhsing On

A more efficient approach would be to convert each list in sets to a set, and filter the edges by whether each set is a superset:

[list(filter(s.issuperset, edges)) for s in map(set, sets)]

This returns:

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

Demo: https://ideone.com/lIDw3G