百度 网站地图怎么做,北京企业网页制作,建筑网址导航大全首页,辽宁建设工程信息网外网公示时间递归函数在函数内部#xff0c;可以调用其他函数。如果一个函数在内部调用自身本身#xff0c;这个函数就是递归函数。举个例子#xff0c;我们来计算阶乘 n! 1 * 2 * 3 * ... * n#xff0c;用函数 fact(n)表示#xff0c;可以看出#xff1a;fact(n) n! 1 * 2 * 3 *…递归函数在函数内部可以调用其他函数。如果一个函数在内部调用自身本身这个函数就是递归函数。举个例子我们来计算阶乘 n! 1 * 2 * 3 * ... * n用函数 fact(n)表示可以看出fact(n) n! 1 * 2 * 3 * ... * (n-1) * n (n-1)! * n fact(n-1) * n所以fact(n)可以表示为 n * fact(n-1)只有n1时需要特殊处理。于是fact(n)用递归的方式写出来就是 def fact(n):
if n1:return 1
return n * fact(n - 1) 如果要计算2的n次方那就是 def fact(n):
if n1:return 1
return 2 * fact(n - 1) 我们可以修改一下代码详细的列出每一步(注意打印出来的内容的顺序哦 def fact(n):print(factorial has been called with n str(n))if n 1:return 1else:res n * fact(n - 1)print(intermediate result for , n, * fact(, n - 1, ): , res)return resprint(fact(10)) 结果是 C:\Python35\python.exe C:/pylearn/bottlelearn/4.py
factorial has been called with n 10
factorial has been called with n 9
factorial has been called with n 8
factorial has been called with n 7
factorial has been called with n 6
factorial has been called with n 5
factorial has been called with n 4
factorial has been called with n 3
factorial has been called with n 2
factorial has been called with n 1
intermediate result for 2 * fact( 1 ): 2
intermediate result for 3 * fact( 2 ): 6
intermediate result for 4 * fact( 3 ): 24
intermediate result for 5 * fact( 4 ): 120
intermediate result for 6 * fact( 5 ): 720
intermediate result for 7 * fact( 6 ): 5040
intermediate result for 8 * fact( 7 ): 40320
intermediate result for 9 * fact( 8 ): 362880
intermediate result for 10 * fact( 9 ): 3628800
1814400000Process finished with exit code 0 进一步思考如果我们想实现递归的效果但是却不想用到递归在python怎么实现呢 def fact(n):result1for i in range(2,n1):resultresult*ireturn resultprint(fact(1))
print(fact(2))
print(fact(10)) 转载于:https://www.cnblogs.com/aomi/p/7047341.html