Recently i encounter with a question about Find the intersection between sublists . that tells the sublist which have any (1 or more ) intersection together become one. for example the following list :
l=[[1,2,3],[0,13,6],[9,10],[3,4,5],[10,11],[6,7,50]]
must be converted to :
[[1, 2, 3, 4, 5],[0, 50, 6, 7, 13],[9, 10, 11]]
So i wrote the following function to do it that works well with a good performance, i use set
for its fast complexity for checking membership and also in inner loop i use slicing that compare the first index of main list with other elements in every loop and also note that the list will been decrease after each loop ,as its a recursion inside the loop . :
s=[set(i) for i in g if i]
def find_intersection(m_list):
for i,v in enumerate(m_list) :
for j,k in enumerate(m_list[i+1:],i+1):
if v & k:
s[i]=v.union(m_list.pop(j))
return find_intersection(m_list)
return m_list
s=[set(i) for i in l if i]
print find_intersection(s)
[set([1, 2, 3, 4, 5]), set([0, 50, 6, 7, 13]), set([9, 10, 11])]
But i think it could be done with another solution maybe with better performance , i thought about collections.deque
or maybe with numpy
or just modifying my function and make it better ? . if you have any suggestion i would be grateful to hear about !
See Question&Answers more detail:
os