了解递归三角数函数

时间:2020-01-28 16:46:19

标签: python python-3.x function recursion math

我有以下递归函数,可返回第n个三角数。例如,当我运行10时,您能解释一下输出如何为how(4)吗?

def how(n):
   if(n==1):
      return 1;
   else:
      return(n+how(n-1))
print(how(4))

1 个答案:

答案 0 :(得分:1)

函数逻辑如下-如果n1,则返回1。否则,返回n + how(n-1)。如果我们逐步完成how(4)的功能,我们可以看到它是如何工作的:

how(4) - returns 4 + how(3)
how(3) - returns 3 + how(2)
how(2) - returns 2 + how(1)
how(1) - returns 1

将所有这些放在一起,以下是等效的:

how(4) - returns 4 + how(3)
how(4) - returns 4 + 3 + how(2)
how(4) - returns 4 + 3 + 2 + how(1)
how(4) - returns 4 + 3 + 2 + 1 = 10
相关问题