Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create an integer array within a recursion?

Tags:

python

arrays

The following code tries to create an integer array filled with n times number 1.

import sys

def foo(n):
    if n == 0:
        return []
    else:
        return foo(n-1).append(1)

if __name__ == '__main__':
    foo(5)

Executing this program yields in an error:

AttributeError: 'NoneType' object has no attribute 'append'

What am I doing wrong when creating the array?

like image 574
John Threepwood Avatar asked Jan 14 '23 02:01

John Threepwood


2 Answers

Just look at the following code to understand why you are getting the error,

>>> x = [].append(1)
>>> x is None
True

When you append to a list, the return value is None! So you must do something like this,

def foo(n):
    if n == 0:
        return []
    else:
        return foo(n-1) + [1]

Using + operator is really like calling extend on a list for which the return value is the new list, unlike append.

>>> x = [1] + [1]
>>> x
[1, 1]

NOTE: Obviously for this simple example you should just use,

>>> [1] * 6
[1, 1, 1, 1, 1, 1]

Which is fine for immutable ints but if you are dealing with objects where you don't want references to the same one,

>>> [1 for _ in range(6)]
[1, 1, 1, 1, 1, 1]

But I'm assuming you are writing this to practice recursive solutions and such.

like image 140
Jared Avatar answered Jan 28 '23 21:01

Jared


The problem is in your else-clause. append does not return a new list, but rather adds an element to the list in-place, and then returns None (hence your error). Try this instead,

return foo(n-1) + [1]  # creates a *new* list
like image 21
arshajii Avatar answered Jan 28 '23 21:01

arshajii