【问题标题】:Repeat function python重复函数python
【发布时间】:2014-06-17 12:55:23
【问题描述】:

我被python中的高阶函数困住了。我需要编写一个重复函数repeat,在给定参数x 上应用函数fn 次。

例如,repeat(f, 3, x)f(f(f(x)))

这就是我所拥有的:

def repeat(f,n,x):
    if n==0:
        return f(x)
    else:
        return repeat(f,n-1,x)

当我尝试断言以下行时:

plus = lambda x,y: repeat(lambda z:z+1,x,y)
assert plus(2,2) == 4

它给了我一个AssertionError。我读到了How to repeat a function n times,但我需要以这种方式完成它,但我无法弄清楚......

【问题讨论】:

  • f(x) 函数是否返回任何内容?除非另有说明,否则将返回None
  • 你想得到f(x)最后一次申请的结果吗?
  • 不应该 repeat 返回类似 return f(repeat(f,n-1,x)) 的东西吗?
  • 作为一个更简单的例子,试试plus(0,2),它应该是2,但你的代码给出了3。它不递归,所以应该很容易调试。
  • 您可以尝试查看plus 的实际返回值,而不仅仅是asserting。尝试使用不同的输入,很容易看出问题所在。

标签: python


【解决方案1】:

你有两个问题:

  1. 你递归的次数错误(如果n == 1,该函数应该被调用一次);和
  2. 您没有在递归调用的返回值上调用 f,因此该函数只会应用一次。

试试:

def repeat(f, n, x):
    if n == 1: # note 1, not 0
        return f(x)
    else:
        return f(repeat(f, n-1, x)) # call f with returned value

或者,或者:

def repeat(f, n, x):
    if n == 0:
        return x # note x, not f(x)
    else:
        return f(repeat(f, n-1, x)) # call f with returned value

(感谢@Kevin,后者支持n == 0)。

例子:

>>> repeat(lambda z: z + 1, 2, 2)
4
>>> assert repeat(lambda z: z * 2, 4, 3) == 3 * 2 * 2 * 2 * 2
>>> 

【讨论】:

  • 最好使用if n == 0: return x 而不是if n == 1: return f(x)。这样,plus(0,2) 仍然可以工作。
【解决方案2】:

你有一个非常简单的错误,在 else 块中你只是传递 x 而不做任何事情。此外,当 n == 0 时,您正在应用 x,不要那样做。

def repeat(f,n,x):
    """
    >>> repeat(lambda x: x+1, 2, 0)
    2
    """
    return repeat(f, n-1, f(x)) if n > 0 else x

【讨论】:

    猜你喜欢
    • 2017-11-15
    • 2013-05-13
    • 2021-08-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-10-26
    • 2015-03-23
    • 2020-12-28
    相关资源
    最近更新 更多