简体   繁体   中英

Making a for-loop that uses a function multiple times

I have a function mul(f,g)

Can anyone show me how I can make a forloop that uses mul(f,g) multiple times?

For example f=(x+1)^3 becomes 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:

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):

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:

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. 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. 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

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