Recursive functions not returning lists as expected

Abhishek Mishra ideamonk at gmail.com
Tue May 4 01:30:34 EDT 2010


Perhaps you forgot a return, thats fundamental to recursion right - funciton
returning itself to itself :)

Here's a bit modification needed -

def recur_trace(x,y):
  print x,y
  if not x:
    return y
  return recur_trace(x[1:], y + x[:1])

print ( recur_trace([],[1,2,3]) )
print
print ( recur_trace([9,8],[1,2,3]) )
print
print ( recur_trace([0],[1,2,3]) )


$ python poo.py
[] [1, 2, 3]
[1, 2, 3]

[9, 8] [1, 2, 3]
[8] [1, 2, 3, 9]
[] [1, 2, 3, 9, 8]
[1, 2, 3, 9, 8]

[0] [1, 2, 3]
[] [1, 2, 3, 0]
[1, 2, 3, 0]


On Tue, May 4, 2010 at 10:32 AM, rickhg12hs <rickhg12hs at gmail.com> wrote:

> Would a kind soul explain something basic to a python noob?
>
> Why doesn't this function always return a list?
>
> def recur_trace(x,y):
>  print x,y
>  if not x:
>    return y
>  recur_trace(x[1:], y + [x[0]])
>
> Here are a couple sample runs.
>
> >>> print(recur_trace([],[1,2,3]))
> [] [1,2,3]
> [1,2,3]
>
> So that worked okay and returned the list [1,2,3].
>
> >>> print(recur_trace([9,8],[1,2,3]))
> [9,8] [1,2,3]
> [8] [1,2,3,9]
> [] [1,2,3,9,8]
> None
>
> No list is returned here.  Why?
> [Using Python 2.6.2]
> --
> http://mail.python.org/mailman/listinfo/python-list
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20100504/120a8ca4/attachment-0001.html>


More information about the Python-list mailing list