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)
但是,是否可以使该术语仅接受 1 个参数?
I'm trying to create a function that takes one argument (a number) and returns the factorial of that number.
For example f(5) will return 1*2*3*4*5
What I have so far is
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)
However, is it possible to make it so that term only takes 1 argument?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
替代实现:
使用递归:
Alternative implementation:
Using recursion:
计算 n 的阶乘是递归函数的标准示例:
Computing the factorial of n is a standard example of a recursive function:
又怎样呢?
What about?
如果您的意思是在
product(n, term)
中,term(n)
应该是一个从索引n
串联到的函数该点的值;那么你的factorial(n)
将被定义为def Factorial(n): return Product(n, Identity)
其中,identity 是defidentity(n): return n
换句话说:
if what you mean is that in
product(n, term)
,term(n)
should be a function from an indexn
in series to the value at that point; then yourfactorial(n)
would be defined asdef factorial(n): return product(n, identity)
where identity isdef identity(n): return n
in other words: