递归阶乘函数 [英] recursive factorial function

查看:92
本文介绍了递归阶乘函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我如何将这两个函数合并为一个递归函数以得到此结果:

how can I combine these two functions in to one recursive function to have this result:

factorial(6)
1! = 1
2! = 2
3! = 6
4! = 24
5! = 120
6! = 720

这些是代码

def factorial( n ):
   if n <1:   # base case
       return 1
   else:
       return n * factorial( n - 1 )  # recursive call
def fact(n):
       for i in range(1, n+1 ):
               print "%2d! = %d" % ( i, factorial( i ) )

fact(6)
1! = 1
2! = 2
3! = 6
4! = 24
5! = 120
6! = 720

如您所见,这两个命令的执行给出了正确的答案,我只想使其成为一个递归函数.

as you see execution of these two gives a correct answer, I just want to make it to one recursive function.

推荐答案

def factorial( n ):
   if n <1:   # base case
       return 1
   else:
       returnNumber = n * factorial( n - 1 )  # recursive call
       print(str(n) + '! = ' + str(returnNumber))
       return returnNumber

这篇关于递归阶乘函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆