How to get the items that multiple lists have in common

1

How do you do when there is no common item, posting notices?

Listing 1, 2, and 3 have different index numbers.

def compabilitySorter (lista1, lista2, lista3):

    listCompatible=[lista1, lista2, lista3]


    checkedItem=set()
    commonItem=set()

    for i in listCompatible:
        for j in i:

            if j in checkedItem:
                commonItem.add(j)
            else:

                checkedItem.add(j)

    return list(commonItem)

Example 1 (Expected Output):

print(compabilitySorter([1, 2, 4],[2],[2, 3, 6]))
>[2]

When there is no common item, it launches a list with numbers that do not have the required response.

Example 2 (Unintended Output):

print(compabilitySorter([1, 2, 4],[3, 5],[2, 3, 6]))
>[2, 3]
    
asked by anonymous 12.12.2018 / 13:42

1 answer

2

"Things in common" in set theory is called intersection . In python, sets (whose translation is literally "sets") have operators and methods ready for you to use.

In this case you can use the intersection method or the & to intersect two or more sets.

conjunto_1 = {1, 2, 3}
conjunto_2 = {2, 3, 4}
conjunto_3 = {3, 4, 5}

print(conjunto_1 & conjunto_2 & conjunto_3)
# >>> {3}

# ou também
print(conjunto_1.intersection(conjunto_2, conjunto_3))
# >>> {3}

To test whether the intersection is empty, simply test the resulting list directly, because collections and empty sequences, when converted to boolean, are False ( Docs ).

print('True' if [] else 'False')  # False
print('True' if [0] else 'False') # True

Then your code could just be:

def compatibilitySorter(lista1, lista2, lista3):
    set1, set2, set3 = set(lista1), set(lista2), set(lista3)
    return list(set1 & set2 & set3)

Using your test samples:

teste1 = compatibilitySorter([1, 2, 4], [2], [2, 3, 6])
print('Interseção:', teste1)

if not teste1:
    print('Interseção vazia, lançar erro...')

print('-' * 15)

teste2 = compatibilitySorter([1, 2, 4], [3, 5], [2, 3, 6])
print('Interseção:', teste2)

if not teste2:
    print('Interseção vazia, lançar erro...')

The output would be:

Interseção: [2]
---------------
Interseção: []
Interseção vazia, lançar erro...

Repl.it with the working code

    
12.12.2018 / 14:07