Python中序列前n项的乘积
我正在尝试创建一个函数,这个函数需要一个参数(一个数字),然后返回这个数字的阶乘。
比如说,f(5) 会返回 1*2*3*4*5 的结果。
我现在的代码是
def product(n, term):
"""Return the product of the first n terms in a sequence.
term -- a function that takes one argument
"""
k, total = 1, 1
while k <= n:
k, total = k + 1, total * term(k, 1)
return total
def factorial(n):
"""Return n factorial by calling product.
>>> factorial(4)
24
"""
return product(n, mul)
不过,能不能让这个函数只接受一个参数呢?
4 个回答
1
计算一个数字n的阶乘是递归函数的一个经典例子:
def fac(n):
return n * fac(n-1) if n > 1 else 1
1
import math
def factorial(n):
return math.factorial(n)
另一种实现方式:
def factorial(n):
return reduce(lambda x,y:x*y,range(1,n+1))
使用递归:
def factorial(n):
if n == 0:
return 1
else:
return n * factorial(n-1)
1
那是关于什么的呢?
import operator
def product(nums):
return reduce(operator.mul, nums, 1)
def factorial(num):
return product(range(2, num+1))