简体   繁体   中英

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

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?

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:

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; then your factorial(n) would be defined as def factorial(n): return product(n, identity) where identity is 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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM