# recursion

3 views

### Gigs_

Sep 13, 2007, 9:59:07 AM9/13/07
to
Can someone explain me this

>>> def f(l):
if l == []:
return []
else:
return f(l[1:]) + l[:1] # <= cant figure this, how is all sum at the end?

thanks!

### Tom Wright

Sep 13, 2007, 10:08:44 AM9/13/07
to

If you think about building up from the simplest case:
f([]) = []
f(['a']) = f([]) + ['a'] = [] + ['a'] = ['a']

Now f(['a', 'b']) is going to be:
f(['b']) + ['a']
= ['b'] + ['a']
= ['b', 'a']

Similarly, for f(['a', 'b', 'c']), that will be:
f(['b', 'c']) + ['a']

Of course, if you want to do this you can always use list.reverse() but I
guess you're trying to get a handle on recursion rather than just reverse a
list. I find thinking up from the base case helps when trying to
understand recursive code but when writing it, I tend to work the other way
around.

--
I'm at CAMbridge, not SPAMbridge

### Neil Cerutti

Sep 13, 2007, 12:01:48 PM9/13/07
to

In plain English, the above program says:

The sum of the items in list l is zero if the list is empty.
Otherwise, the sum is the value of the first item plus the sum of
the rest of the items in the list.

Well, it would say that if it weren't somewhat buggy. l[:1]
doesn't evaluate to a number, but to a list containing one
number, so the above program doesn't do what you say it does.

def my_sum(seq):
if len(seq) == 0:
return 0
else:
return seq[0] + my_sum(seq[1:])

The tough part of recursion is the leap of faith required to
believe that it works. However, you can often use an inductive
proof of correctness to help obviate the faith.

Proof that my_sum(seq) computes the sum of the items in seq (this
proof is modeled on proofs written by Max Hailperin, Barbara
Kaiser, and Karl Knight, in _Concrete Abstractions_):

Base case: my_sum(seq) terminates with value 0 when len(seq) is
zero, because of the evaluation rules for if, len and ==.

Induction hypothesis: Assume that my_sum(subseq) evaluates to
the sum of all the items in subsequence of seq, where 0 <=
len(subseq) < len(seq).

Inductive step: Consider evaluating my_sum(seq) where the
length of seq is greater than 0. This will terminate if
my_sum(seq[1:]) terminates, and will have the value of seq[0] +
my_sum(seq[1:]). Because seq[1:] evaluates to the subsequence of
the rest of the items in seq (all except the first), and 0 <=
len(subseq) < len(seq), we can assume by our induction
hypothesis that my_sum(seq[1:]) does terminate, with a value
equal to the sum of the the rest of the items in seq.
Therefore, seq[0] + my_sum(seq[1:]) evaluates to seq[0] + the
sum of all the items in seq[1:]. Because seq[0] + the sum of
the rest of the items in seq equals the sum of all the items in
seq, we see that my_sum(seq) does terminate with the correct
value for any arbitrary length of seq, under the inductive
hypothesis of correct operation for subsequences of seq.

Conclusion: Therefore, by mathematical induction on the length
of seq, my_sum(seq) terminates with the value of the sum of all
the items in seq for any length of seq.

But really I prefer the first first plain English version. ;)

--
Neil Cerutti
For those of you who have children and don't know it, we have a nursery
downstairs. --Church Bulletin Blooper

### Ian Clark

Sep 13, 2007, 12:14:42 PM9/13/07
to pytho...@python.org
Neil Cerutti wrote:
> On 2007-09-13, Gigs_ <gi...@hi.t-com.hr> wrote:
>> Can someone explain me this
>>
>>>>> def f(l):
>> if l == []:
>> return []
>> else:
>> return f(l[1:]) + l[:1] # <= cant figure this, how is all sum at the end?
>
> In plain English, the above program says:
>
> The sum of the items in list l is zero if the list is empty.
> Otherwise, the sum is the value of the first item plus the sum of
> the rest of the items in the list.

Am I missing something? What does this have to do with summing?

>>> def f(l):
... if l == []:
... return []
... else:
... return f(l[1:]) + l[:1]
...
>>> f([1, 2, 3, 4])
[4, 3, 2, 1]

Ian

### James Stroud

Sep 13, 2007, 1:20:45 PM9/13/07
to

Round Sum

0 f([1, 2, 3, 4])
1 f([2, 3, 4]) + [1]
2 f([3, 4]) + [2] + [1]
3 f([4]) + [3] + [2] + [1]
4 f([]) + [4] + [3] + [2] + [1]

Total [] + [4] + [3] + [2] + [1] = [4, 3, 2, 1]

James

### Neil Cerutti

Sep 13, 2007, 1:32:38 PM9/13/07
to

It says: You need to read more than the first sentence of a
message before responsing:

> Well, it would say that if it weren't somewhat buggy. l[:1]
> doesn't evaluate to a number, but to a list containing one
> number, so the above program doesn't do what you say it does.
>
> It should read something like:
>
> def my_sum(seq):
> if len(seq) == 0:
> return 0
> else:
> return seq[0] + my_sum(seq[1:])

--
Neil Cerutti

### Gigs_

Sep 14, 2007, 7:40:17 AM9/14/07
to
sorry i think that i express wrong. having problem with english

what i mean is how python knows to add all thing at the end of recursion

>>> def f(l):
if l == []:
return []
else:
return f(l[1:]) + l[:1]

f([1,2,3])

recursion1 f([2,3]) + [1]

recursion2 f([3]) + [2] or [2, 1]?

recursion3 f([]) + [3] or [3, 2, 1]

i dont get all this

>>> def f(l):
if l == []:

print l

return []
else:
return f(l[1:]) + l[:1]

>>> f([1,2,3])
[]
[3, 2, 1] # how this come here? how python save variables from each recursion?

sorry again for first post

thanks

### Marc 'BlackJack' Rintsch

Sep 14, 2007, 8:04:51 AM9/14/07
to
On Fri, 14 Sep 2007 13:40:17 +0200, Gigs_ wrote:

> sorry i think that i express wrong. having problem with english
>
>
> what i mean is how python knows to add all thing at the end of recursion

Because you have written code that tells Python to do so. ;-)

> >>> def f(l):
> if l == []:
> return []
> else:
> return f(l[1:]) + l[:1]
>
>
> f([1,2,3])
>
> recursion1 f([2,3]) + [1]
>
> recursion2 f([3]) + [2] or [2, 1]?
>
> recursion3 f([]) + [3] or [3, 2, 1]

Both alternatives in recursion 2 and 3 are wrong. You have to simply
replace the function invocation by its result which gives:

f([1, 2, 3])
r1 f([2, 3]) + [1]
r2 f([3]) + [2] + [1]
r3 f([]) + [3] + [2] + [1]
r4 [] + [3] + [2] + [1]

And now the calls return:

r3 [3] + [2] + [1]
r2 [3, 2] + [1]
r1 [3, 2, 1]

> i dont get all this
>
> >>> def f(l):
> if l == []:
> print l
> return []
> else:
> return f(l[1:]) + l[:1]
>
> >>> f([1,2,3])
> []
> [3, 2, 1] # how this come here? how python save variables from each
> recursion?

There is not just one `l` but one distinct `l` in each call.

Ciao,
Marc 'BlackJack' Rintsch

### Steve Holden

Sep 14, 2007, 8:47:18 AM9/14/07
to pytho...@python.org
I think the thing you are missing is that the recursive call f(l[1:]) in
the return statement causes the current call to be suspended until the
recursive call is complete. The new call has its own value for l, which
is the caller's l[1:]. Each new call creates a completely new namespace.

A less complicated function might make it a little more obvious.

def factorial(n):
print "n =", n
if n=0:
return 1
else:
return n * factorial(n-1)

Try running that with a few different arguments to show you how the
recursion works.

regards
Steve
--
Steve Holden +1 571 484 6266 +1 800 494 3119
Holden Web LLC/Ltd http://www.holdenweb.com
Skype: holdenweb http://del.icio.us/steve.holden

Sorry, the dog ate my .sigline

### John Machin

Sep 14, 2007, 8:53:07 AM9/14/07
to

I reckon that what the OP wants is a simple explanation of how
function calls use a stack mechanism for arguments and local
variables, and how this allows recursive calls, unlike the good ol'
FORTRAN IV of blessed memory. Perhaps someone could oblige him?

I'd try but it's time for my beauty sleep :-)
<yawn>
Good night all
John

### Gigs_

Sep 14, 2007, 9:58:39 AM9/14/07
to
if n==0:

return 1
else:
return n * factorial(n-1)

>>> factorial(3)
n = 3
n = 2
n = 1
n = 0
6

now i understand. but one question at the end this function return 1. how python
knows that it needs to multiply 1 with all recursive returns. (why python didnt
sum recursive return with 1?)

that will be all, thanks in advance

### J. Clifford Dyer

Sep 14, 2007, 9:43:27 AM9/14/07
to Gigs_

On Fri, Sep 14, 2007 at 01:40:17PM +0200, Gigs_ wrote regarding Re: recursion:
>
> what i mean is how python knows to add all thing at the end of recursion
>
> >>> def f(l):
> if l == []:
> return []
> else:
> return f(l[1:]) + l[:1]
>

The following script does exactly the same thing, except it creates print
statements to help you figure out what's going on, and it binds f(L[1:]) to
a variable so you can use it again.

def f(L): # l capitalized to accentuate difference between l and 1.
print "L =", L
print "L[1:] =", L[1:]
print "L[:1] =", L[:1]
if L == []:
print "Return: ", []
return []
else:
next = f(L[1:])
print "Return: ", next, "+", L[:1], "=", next + L[:1]
return next + L[:1]

if __name__=='__main__':
print f(['A', 'B', 'C', 'D'])

Try it out. See what happens.

Cheers,
Cliff

### Neil Cerutti

Sep 14, 2007, 10:20:41 AM9/14/07
to

I may as well stick my neck out again, since I'm already
beautiful. ;)

Another way of understanding recursion is to break it up into
seperate functions, so the spectre of a function calling itself
doesn't appear.

def f(l):
if l == []:
return []
else:
return f(l[1:]) + l[:1]

The function above reverses a list of arbitrary length. To help
understand how it works, I'll write several discreet functions
that sort lists of fixed lengths.

only comes with experience), reversing a two-element list:

def f2(l): # reverse a two-element list
return [l[1], l[0]]

Next build up to the next level, writing a function that can
reverse a three-element list. The key is to be as lazy as
possible. You must figure out a way of taking advantage of the
function that reverses a two-element list. The obvious solution
is to use f2 to reverse the last two elements in our list, and
append the first element in the list to that result:

def f3(l): # reverse a three-element list
return f2(l[1:]) + l[:1]

And so on:

def f4(l):
return f3(l[1:]) + l[:1]

def f5(l):
return f4(l[1:]) + l[:1]

def f6(l):
return f5(l[1:]) + l[:1]

A definite pattern had emerged, and it should be apparent now how
to combine all those functions into one:

def f_(l):
if len(l) == 2:
return [l[1], l[0]]
else:
return f_(l[1:]) + l[:1]

But the function above breaks for lists with less than two items.

>>> f_([1])
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 2, in f2
IndexError: list index out of range

We can handle that. The reverse of a zero or one-element list is
just itself.

def f_(l):
if len(l) < 2:
return l
elif len(l) == 2:
return [l[1], l[0]]
else:
return f_(l[1:]) + l[:1]

And we've arrived at an OK recursive function that can handle
arbitrary length lists. It's not as simple as it could be,
however. A little intuitive leap, perhaps, will allow you to note
that the case of a two-element list can actually be handled
without a special case:

def f(l):
if len(l) < 2:
return l

else:
return f(l[1:]) + l[:1]

Final note: for reasons of tradition, base cases are almost
always set up as it was in the original function, checking for a
zero-length list, and returning a new empty list, the truly
simplest base case. Another intuitive leap is possibly required
to note that a one-element list is not a special case after all:
it's a reverse of a zero-element list with that one element
appended.

def f(l):
if len(l) == 0:

return []
else:
return f(l[1:]) + l[:1]

Clear as mud?

--
Neil Cerutti

### Marc 'BlackJack' Rintsch

Sep 14, 2007, 10:38:16 AM9/14/07
to
On Fri, 14 Sep 2007 15:58:39 +0200, Gigs_ wrote:

> >>> def factorial(n):
> print "n =", n
> if n==0:
> return 1
> else:
> return n * factorial(n-1)
>
> >>> factorial(3)
> n = 3
> n = 2
> n = 1
> n = 0
> 6
>
>
> now i understand. but one question at the end this function return 1. how python
> knows that it needs to multiply 1 with all recursive returns. (why python didnt
> sum recursive return with 1?)

Because there is a ``*`` and not a ``+`` in the last line of the function.

Let's play this through (I abbreviate the function name to just `f()`):

Execution of f(3) leads to the second return:

r1 f(3): return 3 * f(2)

This multiplication can't take place until ``f(2)`` is calculated so the
current function call is "suspended" and evaluated later, when the result
of ``f(2)`` is known. The call in that line is replaces with the result

r2 f(2): return 2 * f(1)

The same again, another call to `f()` with 1 as argument:

r3 f(1): return 1 * f(0)

Now the last call takes the other ``if`` branch:

r4 f(0): return 1

The 1 is returned to the previus call:

r3 f(1): return 1 * 1

This can be evaluated now and is returned to its caller:

r2 f(2): return 2 * 1

Again this is evaluated and returned to its caller:

r1 f(3): return 3 * 2

And here we have the final result that is returned from the first call to
`f()`.

Ciao,
Marc 'BlackJack' Rintsch

### Steve Holden

Sep 14, 2007, 10:47:22 AM9/14/07
to pytho...@python.org
Gigs_ wrote:
> Steve Holden wrote:
[...]

>>
>> regards
>> Steve
> >>> def factorial(n):
> print "n =", n
> if n==0:
> return 1
> else:
> return n * factorial(n-1)
>
> >>> factorial(3)
> n = 3
> n = 2
> n = 1
> n = 0
> 6
>
>
> now i understand. but one question at the end this function return 1. how python
> knows that it needs to multiply 1 with all recursive returns. (why python didnt
> sum recursive return with 1?)
>
>
> that will be all, thanks in advance

Aah, that's the magic of recursion (not that it's really magic at all).

When you call factorial(3), the function sees the value of n as 3. So
the if condition is false, so it must execute the return statement.

In order to do that it has to multiply n by the value of factorial n-1.
So it makes a call to a *new copy* of factorial, and this one has the
value 2 for n. The if statement again needs to execute the return
statement, and before it can do that it needs the value of factorial
n-1, so it makes a call to a *new copy* of factorial, and this one has
the value 1 for n. The if statement again needs to execute the return
statement, and before it can do that it needs the value of factorial
n-1, so it makes a call to a *new copy* of factorial, and this one has
the value 0 for n. [Are you detecting a pattern here?].

Finally *this* copy of factorial can immediately return the value of 1
to its caller, which then multiplies that by 1 and returns it ti *its
caller, which multiplies it by 2 and returns that to *its* caller, when
multiplies it by 3 and returns the result, 6.

In other words, the computer builds a "stack" of partially-completed
functions, and unwinds it when the innermost (topmost, whatever) finally
sees that it can return a result without creating another stacked call
to factorial.

Hope this straightens it out for you, it's a bit of a head-twister when
you first come across it.

### Terry Reedy

Sep 14, 2007, 1:06:03 PM9/14/07
to pytho...@python.org

"Marc 'BlackJack' Rintsch" <bj_...@gmx.net> wrote in message
news:5kvbn3F...@mid.uni-berlin.de...

| f([1, 2, 3])
| r1 f([2, 3]) + [1]
| r2 f([3]) + [2] + [1]
| r3 f([]) + [3] + [2] + [1]
| r4 [] + [3] + [2] + [1]

I might help to note that the above is effectively parenthesized

( ( ([]+{3]) + [2]) +[1])

*and* that each addition (in each pair of parentheses) is done
in a different execution frame (see below).

| And now the calls return:
|
| r3 [3] + [2] + [1]
| r2 [3, 2] + [1]
| r1 [3, 2, 1]

| > [3, 2, 1] # how this come here? how python save variables from each
| > recursion?

*Each time* a function is called, an execution frame is created(1) that is
separate from the function object itself. Each execution frame has its own
set of local variables. In particular, each has its own slices of the
original list.

There have been languages, for instance, Fortran IV, where local variables
were part of the function 'object' and which therefore prohibited recursion
because of the very problem you alluded to in your question. (My guess is
the functions had an InUse flag that was checked when the function was
called.)

tjr

(1) A minor variation would be for function objects to have one
pre-allocated execution frame for non-recursive calls and others allocated
as needed for recursive calls.

### John Machin

Sep 14, 2007, 6:04:01 PM9/14/07
to
On Sep 15, 3:06 am, "Terry Reedy" <tjre...@udel.edu> wrote:
>
> There have been languages, for instance, Fortran IV, where local variables
> were part of the function 'object' and which therefore prohibited recursion
> because of the very problem you alluded to in your question. (My guess is
> the functions had an InUse flag that was checked when the function was
> called.)

No way. Waste of space for instructions to check the flag at the start
and reset it at the end. Waste of CPU time. Divide by zero? Subroutine
calls itself? Drive against the traffic flow on the freeway? Expected
outcome: crash or other unwanted result. Simple: don't do that! Why
bother checking? No self-respecting FORTRAN programmer would want to
use recursion anyway. And mixed case in a variable name? Sheesh.