以下递归功能代码所需的输出

时间:2019-04-28 11:35:44

标签: python

在学习Python并通过了此递归函数后,我浏览了程序,但无法计算出输出

data

输出

def tri_recursion(k):
    if k > 0:
        result = k + tri_recursion(k - 1)
        print(result)
    else:
        result = 0
  return result

print("\n\nRecursion Example Results")
tri_recursion(6)

任何人都可以浏览该程序并向我解释输出吗?

1 个答案:

答案 0 :(得分:0)

您给tri_recursion(6)打过电话 并且,在第三行,退出函数之前先执行tri_recursion函数。 我写的每个步骤如下:

tri_recursion(6) = 6 + tri_recursion(5)                          // 21 is printed
                 = 6 + (5 + tri_recursion(4))                    // 15 is printed
                 = 6 + (5 + (4 + tri_recursion(3))               // 10 is printed
                 = 6 + (5 + (4 + (3 + tri_recursion(2)))         // 6 is printed
                 = 6 + (5 + (4 + (3 + (2 + tri_recursion(1))))   // 3 is printed
                 = 6 + (5 + (4 + (3 + (2 + (1 + tri_recursion(0)))))  // 1 is printed