recursive function with lists

-1

I need to write a recursive function that receives 2 lists and returns a new list with the subtraction of the elements of the first ones, for example:

>>> subtrai([2, 3, 4, 5], [2, 3])  
[4, 5]

I know that I need to know if an element of the 1st list belongs to the 2nd: in the case of belonging this element can not be part of the result, otherwise it belongs.

The problem is that I can not use the remove () function ...

At this point I have the following code

elem = []

if elem in l1 and l2:
    return list(l1-l2)
else:
    return l1

This code returns me only list 1, I can not figure out what I'm doing wrong

Thank you in advance for your help

    
asked by anonymous 23.12.2018 / 19:54

2 answers

0

I believe this implementation will meet your need!

def subtrair(list1, list2):
    for i in list2:
        list1.remove(i)
    return list1
    
23.12.2018 / 23:08
0

It's kind of confusing what you posted, but the feature of recursion 'and it draws itself. As I saw in the statement you can return a third list, then I used an auxiliary counter and a "global" list, the elements will always be put by the append method in "global". if the number exists in the two lists it does not enter the second condition and only calls itself again.

PS: I'm using python3, and for sure there's a better method than mine, but I'm also starting python hope it helps.

def subtrai(list1,list2,contador):

    if len(list1) >contador:

        if not list1[contador] in list2:

            listaDeRetorno.append(list1[contador])

        contador+=1
        subtrai(list1,list2,contador)

    return listaDeRetorno

def main(): 
    list1 = [2,3,4,5,6,7]
    list2 = [5,6,7]
    contador=0
    novaLista = subtrai(list1,list2, contador) 
    print("A nova lista 'e",novaLista)

listaDeRetorno=[] 
main() 
    
28.12.2018 / 05:36