[英]Product of first n terms in a sequence in python
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 例如f(5)将返回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? 但是,是否有可能使该术语仅接受1个参数?
import math
def factorial(n):
return math.factorial(n)
Alternative implementation: 替代实现:
def factorial(n):
return reduce(lambda x,y:x*y,range(1,n+1))
Using recursion: 使用递归:
def factorial(n):
if n == 0:
return 1
else:
return n * factorial(n-1)
Computing the factorial of n is a standard example of a recursive function: 计算n的阶乘是递归函数的标准示例:
def fac(n):
return n * fac(n-1) if n > 1 else 1
What about? 关于什么?
import operator
def product(nums):
return reduce(operator.mul, nums, 1)
def factorial(num):
return product(range(2, num+1))
if what you mean is that in product(n, term)
, term(n)
should be a function from an index n
in series to the value at that point; 如果您的意思是在product(n, term)
, term(n)
应该是从索引n
到该点的值的函数; then your factorial(n)
would be defined as def factorial(n): return product(n, identity)
where identity is def identity(n): return n
那么您的factorial(n)
将被定义为def factorial(n): return product(n, identity)
其中身份为def identity(n): return n
in other words: 换一种说法:
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)
return total
def identity(n):
return n
def factorial(n):
"""Return n factorial by calling product.
>>> factorial(4)
24
"""
return product(n, identity)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.