Help- Simple recursive function to build a list

A

actuary77

I am trying to write simple recursive function to build a list:


def rec(n,alist=[]):
_nl=alist[:]
print n,_nl
if n == 0:
print n,_nl
return _nl
else:
_nl=_nl+[n]
rec(n-1,_nl)

_nl=[]
_nl=rec(4)
print _nl

### shouldn't this work?

_nl=rec(4)




The output is:
4 []
3 [4]
2 [4, 3]
1 [4, 3, 2]
0 [4, 3, 2, 1]
0 [4, 3, 2, 1]
None
None


Question:
============
Why isn't the function returning a list?
Why is function returning None?

Any guidance from one of you pro's would be greatly appreciated.

Thanks,
DKoch
(e-mail address removed)
 
R

Roy Smith

actuary77 said:
I am trying to write simple recursive function to build a list:


def rec(n,alist=[]):
_nl=alist[:]
print n,_nl
if n == 0:
print n,_nl
return _nl
else:
_nl=_nl+[n]
rec(n-1,_nl)

_nl=[]
_nl=rec(4)
print _nl

### shouldn't this work?

_nl=rec(4)




The output is:
4 []
3 [4]
2 [4, 3]
1 [4, 3, 2]
0 [4, 3, 2, 1]
0 [4, 3, 2, 1]
None
None


Question:
============
Why isn't the function returning a list?
Why is function returning None?

I'm not 100% sure what you're trying to do here, but I suspect you left a
"return" out of the else block, i.e. "return rec(n-1, _nl)". That would
certainly explain why it's returning None.

What problem are you trying to solve, or are you just experimenting with
recursion?
 
K

Kent Johnson

actuary77 said:
I am trying to write simple recursive function to build a list:


def rec(n,alist=[]):
_nl=alist[:]
print n,_nl
if n == 0:
print n,_nl
return _nl
else:
_nl=_nl+[n]
rec(n-1,_nl)

should be
return rec(n-1,_nl)
... _nl=alist[:]
... print n,_nl
... if n == 0:
... print n,_nl
... return _nl
... else:
... _nl=_nl+[n]
... return rec(n-1,_nl)
...4 []
3 [4]
2 [4, 3]
1 [4, 3, 2]
0 [4, 3, 2, 1]
0 [4, 3, 2, 1][4, 3, 2, 1]

Kent
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,055
Latest member
SlimSparkKetoACVReview

Latest Threads

Top