Python-为什么要进行8次递归调用?

时间:2018-12-06 16:31:53

标签: python

当前正在审查即将举行的考试,并且收到了此练习题,答案为8,但我不确定为什么。有人可以为我分解吗?我尝试跟踪它,但很快就令人困惑

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

print(confuse('annoy')) 

问题:不包括对confuse('annoy')的调用,在此函数终止之前进行了多少次递归调用?

谢谢!

5 个答案:

答案 0 :(得分:10)

您应该将此画成一棵树:

混淆('annoy'):

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

有八个电话。

答案 1 :(得分:3)

它们被这样称呼:

confuse('annoy')
confuse('an') + confuse('noy')  # 5//2 = 2
confuse('a') + confuse('n') # 2//2 = 1
confuse('n') + confuse('oy') # 3//2 = 1
confuse('o') + confuse('y') # 2//2 = 1

因此,是8。

答案 2 :(得分:3)

confuse('annoy') == confuse('an') + confuse('noy')
                 == confuse('a') + confuse('n') + confuse('n') + confuse('oy')
                 == 'a' + 'n' + 'n' + confuse('o') + confuse('y')
                 == 'a' + 'n' + 'n' + 'o' _ 'y'
                 == 'annoy'

计算在RHS上对confuse的呼叫,您将发现其中的8个。粗略地说,您会收到2**O(lg(n))个递归调用,它们的长度为n

答案 3 :(得分:1)

如果您将代码修改为

def confuse(s):
   print("called with -->", s)
   if len(s) <= 1:        
      return s     
   x = len(s) // 2     
   return confuse(s[:x]) + confuse(s[x:]) 

confuse('annoy')

您将获得

called with --> annoy
called with --> an
called with --> a
called with --> n
called with --> noy
called with --> n
called with --> oy
called with --> o
called with --> y

不包括对confuse('annoy')的调用,在此函数终止之前进行了多少次递归调用? 9-1 = 8

答案 4 :(得分:0)

我希望这段代码能帮助您理解

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

print(confuse('annoy'))