Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python recursion in appending lists

I want to append to a list recursively but I cannot come up with a function that works. The function takes two arguments times and data. times should be the number of times to append the data.

Here is my code so far:

def replicate_recur(times, data):
    result2 = []
    if times == 0:
        result2.append(data)
    else:
        result2.append(data)
        replicate_recur(times - 1, data)
    return result2
like image 349
Nix Avatar asked Feb 22 '17 09:02

Nix


2 Answers

You could use a intermediate list to append to in each recursive call. That avoids these redefinition problems you're encountering currently:

def replicate_recur(times, data, result=None):
    if result is None:  # create a new result if no intermediate was given
        result = []
    if times == 1:
        result.append(data)
    else:
        result.append(data)
        replicate_recur(times - 1, data, result)  # also pass in the "result"
    return result

When called:

>>> replicate_recur(4, 2)
[2, 2, 2, 2]
like image 166
MSeifert Avatar answered Sep 20 '22 21:09

MSeifert


You can use xrange for this, there is no point to use recursion unless it is a coding test.

def replicate(times, data):
    result2 = []
    for i in xrange(times):
        result2.append(data)
    return result2

Same function can be written in a recursive way like this:

def replicate_recur(times, data, listTest=None):
    # If a list has not been passed as argument create an empty one
    if(listTest == None):
        listTest = []
    # Return the list if we need to replicate 0 more times
    if times == 0:
        return listTest
    # If we reach here at least we have to replicate once
    listTest.append(data)
    # Recursive call to replicate more times, if needed and return the result
    replicate_recur(times-1, data, listTest)
    return listTest
like image 41
pushpendra chauhan Avatar answered Sep 17 '22 21:09

pushpendra chauhan