Get common elements from two lists without repetitions

1

I have to implement the following statement:

  

Design a function that receives two lists and returns common elements to   both, without repeating any (intersection of sets).   Example: if you receive the lists [1, 2, 1] and [2, 3, 2, 4], you will return the list [2].

I tried the following:

def listas(a,b):
    lista_final=[]
    for i in a:
        for x in b:
            if i == b:
                lista_final.append(i)
    print (lista_final)

lista=[]
lista2=[]

i=0
while i == 0:
    num=int(input("Escribe una lista de numeros "))
    lista.append(num)
    a=str(input("Pulsa x si quieres acabar: "))
    if a == 'x':
        i=i+1
i=0
while i == 0:
    num2=int(input("Escribe una lista de numeros "))
    lista2.append(num2)
    a=str(input("Pulsa x si quieres acabar: "))
    if a == 'x':
        i=i+1

listas(lista,lista2)

But I always get an empty list and I do not know how to continue.

    
asked by Pedro 08.01.2018 в 13:47
source

1 answer

1

The main idea is yours, but some observations:

  • The comparison if i == b should actually be if i == x . With this you would find only the common elements. But if you have repetitions due to the for nested, for each element present in both lists you will get n * m times that element in the final list (where n is the number of times that element appears in the first list and m which appears in the second).

  • To avoid the above you should check for each iteration that this element is not already in the list of results.

  • To know if an item is in a list in Python, the simplest thing is to use in in a conditional: if elemento in lista: . As you only look for the common elements, it is enough that you iterate on one of the lists.

With this, your code could be:

def listas(a, b):
    lista_final = []
    for i in a:
        if (i not in lista_final) and (i in b):
            lista_final.append(i)
    return lista_final

Example:

>>> lista = [1,2,3,2,4,5]
>>> lista2 = [7,2,5,8,10]
>>> res = listas(lista, lista2)
>>> print(res) 
[2, 5]

Of course, in "real" life it is an extremely inefficient method compared to the intersection of sets already implemented in Python using hash tables:

res = list(set(lista) & set(lista2))
    
answered by 08.01.2018 в 15:01