简体   繁体   中英

Python dual function recursive vs iterative function

Basically, I'm not sure what's wrong with my answer, versus the model answer. What I'm trying to achieve here is to produce a function that can do lambda x: f(g(f(g(f(g(f(x))))))) # for n == 7 or lambda x: f(g(f(g(x)))) # for n == 4

What I've tried

def dual_function(f, g, n):
    if n == 1:
        return f
    elif n % 2 == 0:
        return lambda x: dual_function(f,g, n-1)(g(x))
    else:
        return lambda x: dual_function(f,g, n-1)(f(x))
# the code seems to do the above from my understanding?
# it starts off at n == 7: new_x = f(x)
# n == 6: new_x = g(new_x)
# n == 5: new_x = f(new_x) 
# and so continues down...

The model answer (Sorry i got the wrong model answer for reference, here's the proper one, but now both actually works lol)

    def dual_function(f,g,n):
    def helper(x):
        f1,g1 = f,g
        if n%2==0:
            f1,g1 = g1,f1
        for i in range(n):
            x = f1(x)
            f1,g1= g1,f1
        return x
    return helper

Sample example

f = lambda x: x+1
g = lambda x: x/2
print(dual_function(f, g, 7)(1)) 
# correct answer is 0.9375, versus my wrong answer: 2.0

Your code and the model code seem to be solving different problems. Your code always starts with f(...) as the outermost call (and the innermost call can vary depending on whether n is even or odd), while the reference code always has g(x) as the innermost call (and the outermost call can vary).

So the reason your function isn't matching for n=7 is that you're computing f(g(f(g(f(g(f(x))))))) while the other function is doing g(f(g(f(g(f(g(x))))))) . Unfortunately, I can't tell you which of those is what you're actually supposed to be computing.

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