【发布时间】:2021-06-04 13:54:01
【问题描述】:
我有一个函数mul(f,g)
谁能告诉我如何制作一个多次使用 mul(f,g) 的 forloop?
例如f=(x+1)^3变成mul(f,mul(f,f))
提前致谢!
【问题讨论】:
-
将中间结果保存在循环外的变量中?
标签: python function for-loop recursion expression
我有一个函数mul(f,g)
谁能告诉我如何制作一个多次使用 mul(f,g) 的 forloop?
例如f=(x+1)^3变成mul(f,mul(f,f))
提前致谢!
【问题讨论】:
标签: python function for-loop recursion expression
有趣的练习。由于 mul() 函数不断调用自身,因此根据定义,这就是递归。然而,这不是递归通常的方式,基本情况决定了递归的深度。这里,递归的深度由外部 for 循环确定。这是一种方法:
def f(x):
return x + 1
def mul(f,g):
return(f ** g)
#To calculate (x + 1)^y where x=2 and y=3 , you write the following for loop:
x = 2
y = 3
for g in range(1, y+1):
g = mul(f(x),g)
print(g) #27
#To calculate (x + 1)^y where x=4 and y=2, you write the following for loop:
x = 4
y = 2
for g in range(1, y+1):
g = mul(f(x),g)
print(g) #25
【讨论】:
作为一个 for 循环,@Julia 是正确的,如果方法正确,则将值存储在循环外部:
lst = [1, 2, 3]
product = lst[0]
for n in lst:
product = mult(n, product)
但是,我想指出其他一些替代方案,它们可能在更复杂的情况下有用。首先有一个名为recursion 的概念,这在许多需要在同一个数据结构(在本例中为列表)上或内多次调用同一个函数的情况下很有用:
def pow(n, p):
"""Raise n to a power p"""
if p == 0:
return n
return n * pow(n, p)
lst = [1, 2, 3]
您也可以使用从functools 到reduce 的函数将列表转换为单个值:
import functools
lst = [1, 2, 3]
product = functools.reduce(lambda n, m: n* m, lst)
【讨论】: