如何重复一个函数n次

发布于 2024-12-04 01:13:28 字数 290 浏览 1 评论 0原文

我正在尝试用 python 编写一个函数,如下所示:

def repeated(f, n):
    ...

其中 f 是一个接受一个参数的函数,n 是一个正整数。

例如,如果我将 square 定义为:

def square(x):
    return x * x

并且我称其

repeated(square, 2)(3)

为 3、2 次方。

I'm trying to write a function in python that is like:

def repeated(f, n):
    ...

where f is a function that takes one argument and n is a positive integer.

For example if I defined square as:

def square(x):
    return x * x

and I called

repeated(square, 2)(3)

this would square 3, 2 times.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(7

你的心境我的脸 2024-12-11 01:13:29

应该可以做到:

 def repeated(f, n):
     def rfun(p):
         return reduce(lambda x, _: f(x), xrange(n), p)
     return rfun

 def square(x):
     print "square(%d)" % x
     return x * x

 print repeated(square, 5)(3)

输出:

 square(3)
 square(9)
 square(81)
 square(6561)
 square(43046721)
 1853020188851841

或更少的 lambda ?

def repeated(f, n):
    def rfun(p):
        acc = p
        for _ in xrange(n):
            acc = f(acc)
        return acc
    return rfun

That should do it:

 def repeated(f, n):
     def rfun(p):
         return reduce(lambda x, _: f(x), xrange(n), p)
     return rfun

 def square(x):
     print "square(%d)" % x
     return x * x

 print repeated(square, 5)(3)

output:

 square(3)
 square(9)
 square(81)
 square(6561)
 square(43046721)
 1853020188851841

or lambda-less?

def repeated(f, n):
    def rfun(p):
        acc = p
        for _ in xrange(n):
            acc = f(acc)
        return acc
    return rfun
甜警司 2024-12-11 01:13:29

使用reduce和lamba。
构建一个以您的参数开始的元组,后跟您要调用的所有函数:

>>> path = "/a/b/c/d/e/f"
>>> reduce(lambda val,func: func(val), (path,) + (os.path.dirname,) * 3)
"/a/b/c"

Using reduce and lamba.
Build a tuple starting with your parameter, followed by all functions you want to call:

>>> path = "/a/b/c/d/e/f"
>>> reduce(lambda val,func: func(val), (path,) + (os.path.dirname,) * 3)
"/a/b/c"
怪我入戏太深 2024-12-11 01:13:29

像这样的东西吗?

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

Something like this?

def repeat(f, n):
     if n==0:
             return (lambda x: x)
     return (lambda x: f (repeat(f, n-1)(x)))
百善笑为先 2024-12-11 01:13:29

使用名为 repeatfunc 的 itertools 配方来执行此操作。

给出

def square(x):
    """Return the square of a value."""
    return x * x

代码

来自 itertools Recipes

def repeatfunc(func, times=None, *args):
    """Repeat calls to func with specified arguments.

    Example:  repeatfunc(random.random)
    """
    if times is None:
        return starmap(func, repeat(args))
    return starmap(func, repeat(args, times))

演示

可选:您可以使用第三方库,more_itertools,可以方便地实现这些方法:

import more_itertools as mit


list(mit.repeatfunc(square, 2, 3))
# [9, 9]

通过 > 安装pip 安装 more_itertools

Use an itertools recipe called repeatfunc that performs this operation.

Given

def square(x):
    """Return the square of a value."""
    return x * x

Code

From itertools recipes:

def repeatfunc(func, times=None, *args):
    """Repeat calls to func with specified arguments.

    Example:  repeatfunc(random.random)
    """
    if times is None:
        return starmap(func, repeat(args))
    return starmap(func, repeat(args, times))

Demo

Optional: You can use a third-party library, more_itertools, that conveniently implements these recipes:

import more_itertools as mit


list(mit.repeatfunc(square, 2, 3))
# [9, 9]

Install via > pip install more_itertools

墨洒年华 2024-12-11 01:13:29

使用reduce和itertools.repeat(按照Marcin的建议):

from itertools import repeat
from functools import reduce # necessary for python3

def repeated(func, n):
    def apply(x, f):
        return f(x)
    def ret(x):
        return reduce(apply, repeat(func, n), x)
    return ret

您可以按如下方式使用它:(

>>> repeated(os.path.dirname, 3)('/a/b/c/d/e/f')
'/a/b/c'

>>> repeated(square, 5)(3)
1853020188851841

分别导入os或定义square之后)

Using reduce and itertools.repeat (as Marcin suggested):

from itertools import repeat
from functools import reduce # necessary for python3

def repeated(func, n):
    def apply(x, f):
        return f(x)
    def ret(x):
        return reduce(apply, repeat(func, n), x)
    return ret

You can use it as follows:

>>> repeated(os.path.dirname, 3)('/a/b/c/d/e/f')
'/a/b/c'

>>> repeated(square, 5)(3)
1853020188851841

(after importing os or defining square respectively)

活雷疯 2024-12-11 01:13:29

我认为你想要函数组合:

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

def square(x):
  return pow(x, 2)

y = compose(square, 3, 2)
print y

I think you want function composition:

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

def square(x):
  return pow(x, 2)

y = compose(square, 3, 2)
print y
短暂陪伴 2024-12-11 01:13:29

这里有一个使用reduce的秘诀:

def power(f, p, myapply = lambda init, g:g(init)):
    ff = (f,)*p # tuple of length p containing only f in each slot
    return lambda x:reduce(myapply, ff, x)

def square(x):
    return x * x

power(square, 2)(3)
#=> 81

我称之为power,因为这实际上就是幂函数的作用,用组合代替了乘法。

(f,)*p 创建一个长度为 p 的元组,在每个索引中都填充有 f。如果您想变得更奇特,您可以使用生成器来生成这样的序列(请参阅itertools) - 但请注意它必须在 lambda 内部创建。

myapply 在参数列表中定义,因此仅创建一次。

Here's a recipe using reduce:

def power(f, p, myapply = lambda init, g:g(init)):
    ff = (f,)*p # tuple of length p containing only f in each slot
    return lambda x:reduce(myapply, ff, x)

def square(x):
    return x * x

power(square, 2)(3)
#=> 81

I call this power, because this is literally what the power function does, with composition replacing multiplication.

(f,)*p creates a tuple of length p filled with f in every index. If you wanted to get fancy, you would use a generator to generate such a sequence (see itertools) - but note it would have to be created inside the lambda.

myapply is defined in the parameter list so that it is only created once.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文