Intersection between two sets (element that is in set A and B at the same time)

Asked

Viewed 7,088 times

0

I’m trying to make a function that returns the intersection between two sets:

def intersecao(conjuntoA, conjuntoB):
    inter = [x for x in range(1,12) if x in conjuntoA and conjuntoB]
    return inter

a = [2,4,6,7,10]
b = [3,4,6,8,10,11]
print(intersecao(a,b))

This function should return: [4,6,10] But it is returning: [2, 4, 6, 7, 10] I’ve tried it without understanding lists, but the result is the same... Would someone kindly point out where the mistake is? Because I’ve tried turning it into binary, and it still doesn’t work :/

6 answers

6


The problem with your code is the condition inside the list constructor:

inter = [x for x in range(1,12) if x in conjuntoA and conjuntoB]

You are going through all values from 1 to 11 and checking if it is in set A. The idea would be to check if it is also in set B, but the syntax is wrong. Making:

x in conjuntoA and conjuntoB

What happens, in fact, is that Python will check whether x belongs to the set A and the return of this check will be done the and set B. Since set B is a non-empty list, Python will consider conjuntoB as always true, then the final list will contain all the numbers from 1 to 11 that satisfy the condition x in conjuntoA and True, which will be all elements of A.

How the Python 'in' operator works

To fix this, you can correct the condition:

x in conjuntoA and x in conjuntoB

See working on Ideone.

Note that it is necessary to repeat the part x in. However, another alternative is to use the type set python:

a = set([2,4,6,7,10])
b = set([3,4,6,8,10,11])

print(a.intersection(b)) # {4, 6, 10}

See working on Ideone.

1

1

From what I understand you’re testing in an interval that language already abstracts. That is, Python walks without the need for that range there, unless it needs to return a specific point within the list:

a,b = [2,4,6,7,10],[3,4,6,8,10,11]
intersec = [i for i in b if i in a] ## Retorna o que for comum entre as duas.

1

This is a way to do using 1 for and 1 if only.

def intersecao(lista1, lista2):
    lista3 = []
    for n in lista1:
        if n in lista2:
            lista3.append(n)
    return lista3

# n percorre lista1
# if valida se n esta em lista2
# então faz append em lista3

1

I risk codes in Phyton but I’m not an expert, so sorry if I missed something in the syntax, but you could use the following logic:

    def intersecao(conjuntoA, conjuntoB):
        inter = []
        for x in conjuntoA:
            for y in conjuntoB:
                if x == y:
                    inter.append(x)
        return inter

    a = [2,4,6,7,10]
    b = [3,4,6,8,10,11]
    print(intersecao(a,b))
  • 1

    You can simplify your code by eliminating the second for. Instead of going through the whole set B, you can just do if x in conjuntoB. See: https://ideone.com/B8iGI7

0

To find the interseção of any dois sets we can use the following algorithm...

def intersecao(conjuntoA, conjuntoB):
    inter = list(conjuntoA & conjuntoB)
    inter.sort()

    print(f'\033[32mA interseção entre os conjuntos A e B é: {inter}')


conja = list(map(int, input('Digite os elementos do Conjunto A: ').split()))
conjb = list(map(int, input('Digite os elementos do Conjunto B: ').split()))
a = set(conja)
b = set(conjb)
intersecao(a, b)

See here the functioning of the algorithm.

When this algorithm runs it solicita the typing of all the elements of the set A. Right now we must type all the elements in one line separated by a space.

At that time the values are stored in a lista and then converted into conjuntos.

Then we are asked the elements of the set B.

The interseção dos conjuntos.

Then, to improve the visibility of the results, the set of intersections is converted to lista, next ordenado in increasing form and subsequently exibidos in list form.

Browser other questions tagged

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