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
n?sys.getrecursionlimit()which defaults to10002andf(g(f(g(f(g(f(1))))))) = 2. So the code matches the description. I guess you andthe modelsimply solve slightly different problems.