how do I apply a function n times? [closed]

a 夏天 提交于 2021-02-07 18:27:26

问题


I have been trying without much success to implement a higher order function that would take in repeat(f, n) where f is another function and n is the integer value that says how many times n will be applied to a variable x. For example:

def integer(x):

      x + 1

so i would have repeat (integer, 5) and I would have integer(integer(integer(integer(integer(x)


回答1:


You can use a simple for loop.

>>> def integer_inc(x):
...     return x + 1
... 
>>> def repeat(func, n, x):
...     for i in range(n):
...         x = func(x)
...     return x
... 
>>> repeat(integer_inc, 5, 1)
6
>>>



回答2:


Well, there's the iterative approach:

def repeat(f, n):
    def new_fn(x):
        for _ in range(n):
            x = f(x)
        return x
    return new_fn

higher_fn = repeat(lambda x: x+3, 5)

higher_fn(2)    # => 17 == (((((2 + 3) + 3) + 3) + 3) + 3)

and the compositional approach:

def repeat(f, n):
    new_fn_str = "lambda x: {}x{}".format("f(" * n, ")" * n)
    new_fn     = eval(new_fn_str, {"f": f})
    return new_fn

which results in exactly the same thing but may be slightly faster.




回答3:


We also have the recursive implementation:

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



回答4:


You can create a decorator,

from functools import wraps


def repeat(n=1):
    def decorator(func):
        @wraps(func)
        def wrapper(args):
            args = func(args)
            for i in xrange(n-1):
                args = func(args)
            return args
        return wrapper
    return decorator

if __name__ == "__main__":
    @repeat(n=6)
    def test(a):
        print a
        return a+1
    test(1)


来源:https://stackoverflow.com/questions/28259967/how-do-i-apply-a-function-n-times

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!