How to obtain items that multiple lists have in common

Asked

Viewed 75 times

1

How to do for when there is no common item, launch warnings?

List 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 (Intended output):

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

When there is no common item, launches a list with numbers that have nothing to do with the intended answer.

Example 2 (Output not intended):

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

1 answer

2


"Items 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 method intersection or the operator & to achieve the intersection between 2 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, as collections and empty sequences, when converted to Boolean, are False (Docs).

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

So your code could be just:

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

Using your examples to test:

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 exit would be:

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

Repl.it with the code working

Browser other questions tagged

You are not signed in. Login or sign up in order to post.