Python – Why does this make 8 recursive calls?

  • A+
Category:Languages

Currently reviewing for an upcoming exam, and was given this practice question, the answer is 8, but I am not sure why. Can someone break it down for me? I've tried tracing it, but it got confusing quick hehe.

def confuse(s):         if len(s) <= 1:               return s         x = len(s) // 2         return confuse(s[:x]) + confuse(s[x:])   print(confuse('annoy'))  

Question: Excluding the call to confuse('annoy'), how many recursive calls are made before this function terminates?

Thanks!

 


You should draw this as a tree:

confuse('annoy'):

+- 'an' (half of annoy, rounded down) |  +- 'a' |  /- 'n' /- 'noy'    +- 'n'    /- 'oy'       +- 'o'       /- 'y' 

There's your eight calls.

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: