如何将这两个函数组合到一个递归函数中以获得此结果:
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
正如你看到这两个的执行给出了正确的答案,我只想把它变成一个递归函数。
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
我真的不知道负数的阶乘,但这适用于所有n> = 0:
def factorial(n):
if n >= 0:
if n == 1 or n==0:
return 1
else:
n = n * factorial(n-1)
return n
else:
return 'error'
可以使用这4行代码......
def factorial(n):
f = lambda n: n * f(n - 1) if n > 1 else 1
for x in range(n):
print('{}! = {}'.format(x + 1, factorial(x + 1)))
并且第一次使用递归和while循环计算阶乘。
def factorial(n):
while n >= 1:
return n * factorial(n - 1)
return 1
虽然TrebledJ在关于使用if
的评论中写的选项更好。因为while
循环比SETUP_LOOP, POP_BLOCK
执行更多的操作(if
)。功能较慢。
def factorial(n):
if n >= 1:
return n * factorial(n - 1)
return 1
timeit -n 10000 -r 10
while
每回路836μs±11.8μsif
每回路787μs±7.22μs递归函数中总有某种循环,一些停止循环的停止代码:
public int recursivefactorial(int number)
{
if(number==1)
return 1;
else
return recursivefactorial(number-1)*number;
}
正如您所看到的,实现if
条件会导致实际结束“循环”的代码,这是递归函数中最重要的部分。相反,条件的else
部分导致再次调用recursivefactorial
函数,这实际上是一种循环。
还有一个=)
#FAC calculation
def fakulteta(x):
if x!=1:
return x*fakulteta(x-1)
return 1
print (fakulteta(12))
2行代码:
def fac(n):
return 1 if (n < 1) else n * fac(n-1)
测试一下:
print fac(4)
结果:
24
一个简短的:
def fac(n):
if n == 0:
return 1
else:
return n * fac(n-1)
print fac(0)
def factorial(n):
result = 1 if n <= 1 else n * factorial(n - 1)
print '%d! = %d' % (n, result)
return result
试试这个:
def factorial( n ):
if n <1: # base case
print "%2d! = %d" % (n, n)
return 1
else:
temp = factorial( n - 1 )
print "%2d! = %d" % (n, n*temp)
return n * temp # recursive call
我注意到的一件事是你为n <1返回'1',这意味着即使是负数,你的函数也会返回1。你可能想解决这个问题。
我没有Python的经验,但这样的事情?
def factorial( n ):
if n <1: # base case
return 1
else:
f = n * factorial( n - 1 ) # recursive call
print "%2d! = %d" % ( n, f )
return f
fac = lambda x: 1 if x == 0 else x * fac(x - 1)
这个功课是否有机会?
def traced_factorial(n):
def factorial(n):
if n <= 1:
return 1
return n * factorial(n - 1)
for i in range(1, n + 1):
print '%2d! = %d' %(i, factorial(i))
给PEP227一个阅读更多细节。缺点是Python允许您在函数中定义函数。
多一个
def fact(x):
if x == 0:
return 0
elif x == 1:
return 1
else:
return x * fact(x-1)
for x in range(0,10):
print '%d! = %d' %(x, fact(x))