简体   繁体   English

Python双函数递归与迭代函数

[英]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 我在这里想要实现的是生成一个可以执行lambda x: f(g(f(g(f(g(f(x))))))) # for n == 7lambda 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). 您的代码始终以f(...)作为最外层调用(并且最里面的调用会根据n是偶数还是奇数而变化)开始,而参考代码始终以g(x)作为最内层调用(也是最外层调用g(x)电话可能会有所不同)。

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))))))) . 因此,您的函数与n=7不匹配的原因是,您正在计算f(g(f(g(f(g(f(x)))))))而另一个函数正在执行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. 不幸的是,我无法告诉您实际上应该计算的是哪一个。

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

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