简体   繁体   English

制作一个多次使用 function 的 for 循环

[英]Making a for-loop that uses a function multiple times

I have a function mul(f,g)我有一个 function mul(f,g)

Can anyone show me how I can make a forloop that uses mul(f,g) multiple times?谁能告诉我如何制作一个多次使用 mul(f,g) 的forloop?

For example f=(x+1)^3 becomes mul(f,mul(f,f))例如f=(x+1)^3变为mul(f,mul(f,f))

Thanks in advance!提前致谢!

As a for loop @Julia is right an storing the value external to the loop if the right approach:作为 for 循环,@Julia 是正确的,如果方法正确,则将值存储在循环外部:

lst = [1, 2, 3]
product = lst[0]

for n in lst:
    product = mult(n, product)

However there are a few other alternatives that I want to point out, that could be useful in more complex situations.但是,我想指出其他一些替代方案,它们在更复杂的情况下可能很有用。 First there is concept called recursion which is helpful in many cases where you need to call the same function multiple times on or within the same data structure (in this case a list):首先,有一个称为递归的概念,这在许多情况下很有帮助,您需要在同一数据结构上或内部多次调用相同的 function(在本例中为列表):

def pow(n, p):
    """Raise n to a power p"""
    if p == 0:
        return n
    return n * pow(n, p)
lst = [1, 2, 3]

You may also use a function from functools to reduce a list into a single value:您还可以使用functools中的 function 将列表reduce为单个值:

import functools

lst = [1, 2, 3]
product = functools.reduce(lambda n, m: n* m, lst)

Interesting exercise.有趣的练习。 Since the mul() function keeps calling itself, this is, by definition, recursion.由于 mul() function 一直在调用自己,根据定义,这就是递归。 However, it is not the way recursion is usually done, where the base case determines the depth of recursion.然而,这不是递归通常的方式,基本情况决定了递归的深度。 Here, the depth of recursion is determined by an external for loop.这里,递归的深度由外部 for 循环确定。 Here is one way to do it:这是一种方法:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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