English 中文(简体)
如何重复职能
原标题:How to repeat a function n times
  • 时间:2011-09-09 09:47:54
  •  标签:
  • python

我试图在晚间书写一种功能,即:

def repeated(f, n):
    ...

<代码>f是一种带有一个论点的功能,n是一种积极的分类。

例如,如果我界定了广场为:

def square(x):
    return x * x

我呼吁

repeated(square, 2)(3)

这将为3,2次。

问题回答

应:

 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 -less?

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

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"

Something like this?

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

采用一种称为<代码>的惯性ool/代码>来进行这一操作。

<><0>

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

<><><>>>>

https://docs.python.org/3/library/itertools.html#itertools-recipes”rel=“nofollow noreferer”>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

(如马克宁建议的那样):

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

(在分别进口<条码>、/code>或定义<条码>后)

我认为,你想要的是职能构成:

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

此处采用<代码>reduce<>/code>的对应法:

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/code>,因为这实际上是权力功能,其组成取代了重叠。

(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在参数清单中作了界定,因此,该表只设定一次。





相关问题
Can Django models use MySQL functions?

Is there a way to force Django models to pass a field to a MySQL function every time the model data is read or loaded? To clarify what I mean in SQL, I want the Django model to produce something like ...

An enterprise scheduler for python (like quartz)

I am looking for an enterprise tasks scheduler for python, like quartz is for Java. Requirements: Persistent: if the process restarts or the machine restarts, then all the jobs must stay there and ...

How to remove unique, then duplicate dictionaries in a list?

Given the following list that contains some duplicate and some unique dictionaries, what is the best method to remove unique dictionaries first, then reduce the duplicate dictionaries to single ...

What is suggested seed value to use with random.seed()?

Simple enough question: I m using python random module to generate random integers. I want to know what is the suggested value to use with the random.seed() function? Currently I am letting this ...

How can I make the PyDev editor selectively ignore errors?

I m using PyDev under Eclipse to write some Jython code. I ve got numerous instances where I need to do something like this: import com.work.project.component.client.Interface.ISubInterface as ...

How do I profile `paster serve` s startup time?

Python s paster serve app.ini is taking longer than I would like to be ready for the first request. I know how to profile requests with middleware, but how do I profile the initialization time? I ...

Pragmatically adding give-aways/freebies to an online store

Our business currently has an online store and recently we ve been offering free specials to our customers. Right now, we simply display the special and give the buyer a notice stating we will add the ...

Converting Dictionary to List? [duplicate]

I m trying to convert a Python dictionary into a Python list, in order to perform some calculations. #My dictionary dict = {} dict[ Capital ]="London" dict[ Food ]="Fish&Chips" dict[ 2012 ]="...

热门标签