Andre
Andre

Reputation: 1661

appending LinkedLists items to list using Recursion

I have this:

def ppend(n):
    lis = []
    if n.rest == None:
        pass
    else:

        lis.append(n.first)
        ppend(n.rest)

    return lis

n is a linked-list [1,2,3]

The output I am getting is :

[1]

But the output I am looking for is:

[1,2,3]

Upvotes: 1

Views: 42

Answers (1)

Justin O Barber
Justin O Barber

Reputation: 11591

You are creating a new lis list on every recursion. (Incidentally, you might try to find more descriptive names.) Only the first list is returned, however, because you don't do anything with the other lists that result from recursion. Instead, you simply call the function, which simply creates a new list without doing anything with the value returned by the function. You can see this in the following line:

ppend(n.rest)  # a new list is created but nothing is done with the result of the function

If you only plan to use the function once, you can simply move the lis assignment outside of the function:

lis = []

def ppend(n):
    if n.rest is not None:  # the first if statement appears unnecessary
        lis.append(n.first)
        ppend(n.rest)
    return lis  # or don't return it but simply refer to lis where you need to

The above approach, however, will not work as well if you plan to use the function multiple times and always need a new list. In the latter case, you might add a second function like this:

def make_ppend(n, lis):  # add lis as a parameter to be explicit, but you could rely on scope instead of adding this extra parameter
    if n.rest is not None:
        lis.append(n.first)
        make_ppend(n.rest, lis)

def ppend(n):
    lis = []  # now in the local scope
    make_ppend(n, lis)
    return lis

I am guessing you are after something like the second solution.

Upvotes: 2

Related Questions