没有 0 的新阶乘函数
New factorial function without 0
因此,python中的标准阶乘函数定义为:
def factorial(x):
if x == 0:
return 1
else:
return x * factorial(x-1)
自 n! := n * (n-1) * ... * 1,我们可以写n!作为(n + 1)! /(n+1)。因此 0! = 1,如果 x == 0,我们就不需要它了。我试着把它写在 python 中,但我没有工作。你们能帮帮我吗?
因为这是一个递归函数 (return x * factorial(x-1)
),所以你必须有一个结束条件 (if x == 0:
)。
确实 n! == (n+1)! / (n+1)
并且您可以将递归调用更改为:
def factorial(x):
return factorial(x+1) / (x+1)
但这又没有结束条件 -> 无限递归(你将调用下一个 (n+1)!然后调用 (n+2)!等等直到永远(或者直到你得到一个例外)).
顺便说一句,您可以让条件在 1:
处停止执行
if x == 1:
return 1
你不会想对不受限制的东西使用递归函数,因此我建议从标准库中导入一些东西
from functools import reduce
import operator
def fact(x):
if not isinstance(x, int) or x <= 0:
raise Exception("math error")
else:
return reduce(operator.mul, range(1, x + 1), 1)
print(fact("string"))
print(fact(-5))
print(fact(0))
print(fact(5))
刚刚意识到没有必要那么忙:
def fact2(x):
if not isinstance(x, int) or x <= 0:
Exception("math error")
else:
y = 1
while x > 1:
y *= x
x -= 1
return y
因此,python中的标准阶乘函数定义为:
def factorial(x):
if x == 0:
return 1
else:
return x * factorial(x-1)
自 n! := n * (n-1) * ... * 1,我们可以写n!作为(n + 1)! /(n+1)。因此 0! = 1,如果 x == 0,我们就不需要它了。我试着把它写在 python 中,但我没有工作。你们能帮帮我吗?
因为这是一个递归函数 (return x * factorial(x-1)
),所以你必须有一个结束条件 (if x == 0:
)。
确实 n! == (n+1)! / (n+1)
并且您可以将递归调用更改为:
def factorial(x):
return factorial(x+1) / (x+1)
但这又没有结束条件 -> 无限递归(你将调用下一个 (n+1)!然后调用 (n+2)!等等直到永远(或者直到你得到一个例外)).
顺便说一句,您可以让条件在 1:
处停止执行if x == 1:
return 1
你不会想对不受限制的东西使用递归函数,因此我建议从标准库中导入一些东西
from functools import reduce
import operator
def fact(x):
if not isinstance(x, int) or x <= 0:
raise Exception("math error")
else:
return reduce(operator.mul, range(1, x + 1), 1)
print(fact("string"))
print(fact(-5))
print(fact(0))
print(fact(5))
刚刚意识到没有必要那么忙:
def fact2(x):
if not isinstance(x, int) or x <= 0:
Exception("math error")
else:
y = 1
while x > 1:
y *= x
x -= 1
return y