recursion

Gigs_ gigs at hi.t-com.hr
Fri Sep 14 09:58:39 EDT 2007


Steve Holden wrote:
> 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
>>
>>  >>> 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
>>
> 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
 >>> 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



More information about the Python-list mailing list