重复函数python

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/24264420/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 04:20:38  来源:igfitidea点击:

Repeat function python

python

提问by username_HI

I'm stuck at higher-order functions in python. I need to write a repeat function repeatthat applies the function fntimes on a given argument x.

我被困在 python 中的高阶函数。我需要编写一个重复函数repeat,将函数fn时间应用于给定参数x

For example, repeat(f, 3, x)is f(f(f(x))).

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

This is what I have:

这就是我所拥有的:

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

When I try to assert the following line:

当我尝试断言以下行时:

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

It gives me an AssertionError. I read about How to repeat a function n timesbut I need to have it done in this way and I can't figure it out...

它给了我一个AssertionError. 我读过如何重复函数 n 次,但我需要以这种方式完成它,但我无法弄清楚......

采纳答案by jonrsharpe

You have two problems:

你有两个问题:

  1. You are recursing the wrong number of times (if n == 1, the function should be called once); and
  2. You aren't calling fon the returned value from the recursive call, so the function is only ever applied once.
  1. 您递归的次数错误(如果n == 1,该函数应该被调用一次);和
  2. 您没有调用f递归调用的返回值,因此该函数只应用一次。

Try:

尝试:

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

or, alternatively:

或者,或者:

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

(thanks to @Kevin for the latter, which supports n == 0).

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

Example:

例子:

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

回答by A_User

You've got a very simple error there, in the else block you are just passing x along without doing anything to it. Also you are applying x when n == 0, don't do that.

你在那里有一个非常简单的错误,在 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