Search code examples
pythonsetoverlap

Find groups of 3-element sets that DO not share elements (no overlap whatsoever) in a list


I've found an algorithm that will sort through a list and display each value of the list of sets and find all sets that do not overlap.

Example

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

for a in range(0, len(c)):
    for b in range(o, len(c)):
        if c[a] does not overlap c[b]:
            new_list.append(c[a] and c[b]:
              # example [1,2,3],[4,5,6]
            if c[b] does not overlap all of new_list:
              # example can't use [4,3,2] because 4 is already in one of the sets
               new_list.append([7,9,8])

Intended output

[1,2,3],[4,5,6],[7,8,9]
  • Please don't worry about [4,3,2],[7,8,9]. I intend to use this for loop in a while loop for the other indices later.

Question

Is there any pre-existing sorting algorithm in python that will do as I intend?


Solution

  • Here's a version of your algorithm that uses a set for checking whether values in a list have been seen before:

    c = [[1,2,3],[4,3,2],[4,5,6],[9,5,8],[7,8,9]]
    
    new = []
    s = set()
    
    for l in c:
        if not any(v in s for v in l):
            new.append(l)
            s.update(l)
    
    print(new)
    

    Output:

    [[1, 2, 3], [4, 5, 6], [7, 8, 9]]