Home > OS >  Python Recursive Function not returning list
Python Recursive Function not returning list

Time:05-01

Just practicing some assignments in an algorithms textbook using python3. This function is supposed to read a list/array of integers and return a new list/array of only the even integers. I feel like my implementation is correct but it is not returning the list as I expect.

Here is my function, and a quick test for it. I am printing out the length of the array as it is returned (6), and then printing the length immediately when the function is called (None)

def even_array(array1, new_array=[], index=0):
    if index >= len(array1):
        print(len(new_array))
        return new_array
    else:
        if(array1[index] % 2) == 0: #this is an even number
            new_array.append(array1[index])
        even_array(array1, new_array, index   1)


int_array = [1,2,3,4,5,5,6,99,102,104,22]

new_array = even_array(int_array)
print(len(new_array))

new_array = even_array(int_array)
for element in new_array:
    print(element)

This is my first post on here, so any feedback on formatting or how much info I should include is appreciated :)

CodePudding user response:

Your else case is missing a return statement, so the value isn't returned.

def even_array(array1, new_array=[], index=0):
    if index >= len(array1):
        print(len(new_array))
        return new_array
    else:
        if(array1[index] % 2) == 0: #this is an even number
            new_array.append(array1[index])
        return even_array(array1, new_array, index   1)

Side note: don't pass an empty array as a default argument, that's an easy way to introduce hard to debug issues. Read this answer for better clarity.

CodePudding user response:

Your idea is good, but there are a few issues with the execution.

  1. You are missing a return statement in the else branch;
  2. You are modifying a list parameter. This will make things hard to follow, as it will retain all changes done by all the recursive calls. This is to be avoided in general.

A possible fix:

def even_array(array1, new_array=[], index=0):
    if index >= len(array1):
        print(len(new_array))
        return new_array
    else:
        if(array1[index] % 2) == 0: #this is an even number
            return even_array(array1, new_array   [array1[index]], index   1)

You can do it with .append too in this case, since there is nothing else being done after the recursive call. If there were another recursive call for example, you would likely need to have a corresponding .pop call. But if possible, avoid mutating list parameters like this.

  • Related