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

0

I'm trying to do 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 have tried other than by list understanding, but the result is the same ... Could someone point out where the error is by courtesy? Pq to turning into binary I already tried, and still not true: /

    
asked by anonymous 26.08.2017 / 01:07

5 answers

4

The problem in 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 traversing 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. Doing:

x in conjuntoA and conjuntoB
What actually happens is that Python will check if x belongs to set A and the return of this check will be done and with set B. Since set B is a non-empty list, Python will consider conjuntoB as true always, so 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 'in' operator works in Python

To fix this, you can fix the condition:

x in conjuntoA and x in conjuntoB
  

See working at Ideone .

Notice that it is necessary to repeat the x in part. However, another alternative is to use the set type of 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 at Ideone .

    
26.08.2017 / 03:37
0

I risk code in Phyton but I'm not an expert, so I'm sorry 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))
    
26.08.2017 / 02:22
0

If you need operations between sets, just use set:

a = {1, 2, 3, 4, 5}
b = {0, 3, 4, 6, 7, 10}
intersecao = (a & b)

link

    
01.09.2017 / 05:45
0

This is a way to do it 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
    
15.05.2018 / 14:42
0

From what I've noticed, you're testing in a range that language already abstracts. That is, Python runs without the need of this 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.
    
02.08.2018 / 19:14