How to create an integer array in recursion?

The following code attempts to create an integer array filled with the n times number character.

 import sys def foo(n): if n == 0: return [] else: return foo(n-1).append(1) if __name__ == '__main__': foo(5) 

Running this program results in an error:

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

What am I doing wrong when creating an array?

+4
source share
5 answers

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 
+4
source

Take a look at the following code to see why you get the error,

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

When added to the list, the return value is None ! So you should do something like this,

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

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

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

NOTE. Obviously, for this simple example, you should simply use

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

This is normal for immutable int , but if you are dealing with objects where you do not want to refer to the same,

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

But I assume that you write this to practice recursive solutions, etc.

+4
source

it might be worth noting that python has good syntax to cover your usecase:

 >>> [1]*5 [1, 1, 1, 1, 1] 
+3
source

Your program has changed slightly

 import sys def foo(n): if n == 0: return [] else: return foo(n-1) + [1] if __name__ == '__main__': print(foo(5)) 

Print

 [1, 1, 1, 1, 1] 

list.append() modifies the list but returns nothing. That way, recursions of your function that reach this branch actually don't return anything or None .

The method I have listed adds an element to the list, and then returns the list, so your recursion works the way you wanted.

+1
source

append returns None . This is problem.

-3
source

Source: https://habr.com/ru/post/1487137/


All Articles