Get the number of common elements from two lists

0

I am implementing the python code for this statement: Implement a function called cantAparicionesSub that take two integer lists as a parameter, and calculate the amount of elements of the first list that are also in the second. Also return a list with the common elements between the two lists.

For this I wrote this code:

def cantAparicionesSub(lista1, lista2):
    lista_final = []
    contador = 0

    for i in range( len(lista1) ):
        for j in range( len(lista2) ):
            if lista1[i] == lista2[j]:
                lista_final.append(i)
                contador = contador + 1
    print("Cantidad de elementos comunes: ", contador)
    return contador, lista_final

Testing, for example with:

listaA = [1,1,1,1,1,1,2]
listaB= [1]
res = cantAparicionesSub(listaA, listaB)
print(res)

It results in 6 elements of the listA that are in B. But the list of common elements gives: [0, 1, 2, 3, 4, 5]. Always generate a list with the increase of i and I have not managed to obtain the expected list.

    
asked by jsuarezbaron 25.09.2018 в 05:27
source

2 answers

0

Some things are not explained well. For example: If "listB" has more than one element that matches "listA", is more than one counter or the total number of repetitions returned? Can the "listB" have elements that are repeated? Does the final list only bring up the coincidence of each element, or all the times that it is in the "listA"?

To count the number of matches for an item in a list, there is the function count link

Well, as I put it, the problem has ambiguities, but this code can help you find what you want if it does not serve you exactly. Returns the number of matches in a list and another list with matching items.

def cantAparicionesSub(lista1, lista2):
    contador = 0
    lista_final = []
    for n in lista2:
        num_ocurrencias = lista1.count(n)
        if num_ocurrencias > 0:
            contador += num_ocurrencias
            lista_final.append(n)
    return contador, lista_final

listaA = [1,1,1,1,1,1,2]
listaB = [1]
res = cantAparicionesSub(listaA, listaB)
print(res)

Result

(6, [1])

(6 times item 1 is repeated)

Another example, for lists

listaA = [1,1,1,1,1,1,2,3,3,3]
listaB = [1,3,5]

The result would be:

(9, [1, 3])

(9 times are repeated together 1 and 3)

    
answered by 25.09.2018 / 07:38
source
0

The line of code that is generating the problem is:

end_list.append (i)

This line is adding the position "i" where the element "list1 [i]" is to the end_list, to add the element of the list1 in the end_list the code would be the following:

list_final.append (list1 [i]) or list_final.append (list2 [i])

Luck.

    
answered by 25.09.2018 в 08:54