recursive function with lists

Asked

Viewed 433 times

-2

I need to write a recursive function that takes 2 lists and returns a new list by subtracting the elements from the first ones, for example:

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

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

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

Right now 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’t figure out what I’m doing wrong

I thank you in advance for your help

2 answers

0

I believe this implementation will meet your need!

def subtrair(list1, list2):
    for i in list2:
        list1.remove(i)
    return list1
  • Yes, this implementation would be the solution. However, I cannot use the remove() function. That’s why I can’t solve the problem.

  • @rguest can use del?

  • Since del does the same function that removes it (if I am not mistaken, if you are please clarify me), I guess I could not have used it either. So I chose to use remove anyway.

0

Guy’s kind of confused what he posted, but the characteristic of recursion 'and it call itself. As I saw in the statement Voce can return a third list, so I used an auxiliary counter and a "global" list, the elements will always be placed by the append method in the "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 there sure is a better method than mine, but I’m also getting 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() 

Browser other questions tagged

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