python - double recursive education example -


this function not making sense me. ive added print statements on place figure out whats going on , still dont it. i'd grateful if explain me.

def f(s):     if len(s) <= 1:         return s     return f(f(s[1:])) + s[0]  print(f("mat")) 

this see happening. start string of length 3 , bypass if statement. work on inside f(s[1:]) first. have string of length 2 ("at") again bypasses if statement , enters f(s[1]) gives string of length 1 ("t") enters if statement , returns "t". trail goes cold me.

from print statements, see new string of length 2 created , subsequent "a" gets returned. final product ends being "atm". "m" being tagged on end "+ s[0]" part why "atm" , not "tam"?

i've spent few hours on , cant make rain. appreciated.

expand whole thing out long steps filling in function calls doing. deal brackets deepest/most embedded first. deal function calls before addition.

i'm going ignore string quotes everywhere clarity.

f(mat)           -> mat 3 chars:                     call f on @ f(at), , call f on that.                     add m.  f(f(at))+m       -> inner f(at), @ 2 chars:                     call f on t f(t), , call f on that.                     add a.  f(f(f(t))+a)+m   -> innermost f(t) returns t.  f(f(t)+a)+m      -> inner f(t) returns t well.  f(ta)+m          -> [here, first f(f(at)) has been reduced f(ta)]                     ta 2 chars:                     call f on f(a), , call f on that.                     add t.  f(f(a))+t+m      -> inner f(a) returns a.  f(a)+t+m         -> f(a) returns well.  + t + m        ->   atm              -> reduces atm. 

Comments

Popular posts from this blog

powershell Start-Process exit code -1073741502 when used with Credential from a windows service environment -

twig - Using Twigbridge in a Laravel 5.1 Package -

c# - LINQ join Entities from HashSet's, Join vs Dictionary vs HashSet performance -