Home > Mobile >  Remove common in two list
Remove common in two list

Time:09-18

I have problem with Python function uncommon(l1,l2) that takes two lists sorted in ascending order as arguments and returns the list of all elements that appear in exactly one of the two lists. The list returned should be in ascending order. All such elements should be listed only once, even if they appear multiple times in l1 or l2.

Thus, uncommon([2,2,4],[1,3,3,4,5]) should return [1,2,3,5] while uncommon([1,2,3],[1,1,2,3,3]) should return []

I have tried

def uncommon(l1,l2):
  sl1=set(l1)

CodePudding user response:

Using sets is a good start - sets have good logic regarding group operations.
If we think using venn diagrams we can see that "uncommon" elements are everything that is in the Union of the two lists minus the intersection of the two lists (the part in white is the intersection):

In python, this is called symmetric difference, and is built into sets:

def uncommon(l1, l2):
    set1 = set(l1)
    set2 = set(l2)
    return sorted(list(set1.symmetric_difference(set2)))


print(uncommon([2, 2, 4], [1, 3, 3, 4, 5]))  # [1, 2, 3, 5]
print(uncommon([2, 2, 4], [1, 3, 3, 4, 5, 255]))  # [1, 2, 3, 5, 255]
print(uncommon([1, 2, 3], [1, 1, 2, 3, 3]))  # []

CodePudding user response:

For a solution that doesn't require sorting (O(n*logn)), you can merge the sorted lists with heapq.merge after removing the duplicates and intersections:

from heapq import merge

def uncommon(l1,l2):
    d1 = dict.fromkeys(l1)
    d2 = dict.fromkeys(l2)
    drop = set(d1).intersection(d2)
    return list(merge(*([x for x in d
                         if not x in drop]
                        for d in [d1, d2])))

uncommon([2,2,4], [1,3,3,4,5,256])
# [1, 2, 3, 5, 256]

CodePudding user response:

To get the uncommon element from two lists remove the common elements from the union(list1 list2) of the two lists.

def uncommon(l1,l2):
    l1 = set(l1)
    l2 = set(l2)
    return sorted(list(l1.union(l2) - (l1.intersection(l2))))


print(uncommon([2,2,4],[1,3,3,4,5]))
print(uncommon([1,2,3],[1,1,2,3,3]))

OUTPUT

[1, 2, 3, 5]
[]

CodePudding user response:

The common elements are those contained in both lists. So first get rid of elements in list 1 that are also in list 2. Then get rid of elements in list 2 that are also in list 1. Return the remaining elements.

def uncommon(l1, l2):
    d1=l1-l2
    d2=l2-l1
    return d1 d2
  • Related