Skip to content

Problem 2: Product (100pts)

Problem

The summation(n, f) function from the higher-order functions lecture adds up f(1) + ... + f(n). Write a similar function called product that returns f(1) * ... * f(n).

来自高阶函数讲座中的 summation(n, f) 函数计算的是 f(1) + ... + f(n) 的和。请编写一个类似的函数,名为 product,它返回 f(1) * ... * f(n) 的乘积。

def product(n, f):
    """Return the product of the first n terms in a sequence.
    n -- a positive integer
    f -- a function that takes one argument to produce the term

    >>> product(3, identity)  # 1 * 2 * 3
    6
    >>> product(5, identity)  # 1 * 2 * 3 * 4 * 5
    120
    >>> product(3, square)    # 1^2 * 2^2 * 3^2
    36
    >>> product(5, square)    # 1^2 * 2^2 * 3^2 * 4^2 * 5^2
    14400
    >>> product(3, increment) # (1+1) * (2+1) * (3+1)
    24
    >>> product(3, triple)    # 1*3 * 2*3 * 3*3
    162
    """
    "*** YOUR CODE HERE ***"

Hints

  • 注意初始值是1,不是0

Solutions

使用 while 循环。

def product(n, f):
    # 初始化乘积为 1
    result = 1

    # 计数器/项数索引 k,从序列的第一项 k=1 开始
    k = 1

    # 使用 while 循环,从 k=1 迭代到 k=n
    while k <= n:
        # 1. 计算当前项的值:f(k)
        current = f(k)

        # 2. 将当前项乘入总乘积中
        result *= current

        # 3. 递增 k,移至序列的下一项
        k = k + 1

    # 循环结束后,输出 result
    return result

递归(压行)

def product(n, f):
    return f(1) if n == 1 else f(n) * product(n - 1, f)