Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Apply function n-times, using output of last as input of next

Tags:

python

For example, when traversing multiple levels up a hierarchy using dirname I typically do this.

grandparent = os.path.dirname(__file__)
grandparent = os.path.dirname(grandparent)

Or, in case of more levels.

grandparent =  = os.path.dirname(__file__)
for x in xrange(5):
  grandparent = os.path.dirname(grandparent)

But I wonder if there's a less verbose method of doing this?

Such as

grandparent = y(5, os.path.dirname, __file__)

Where y is the mysterious function I'm looking for.

And if not, what would such a function be called?

like image 585
Marcus Ottosson Avatar asked Oct 19 '22 10:10

Marcus Ottosson


1 Answers

What about defining such higher order function yourself:

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

With f the function you wish to call, x the first input in the sequence, and n the number of times you wish to call this.

You can then call it for instance with:

>>> repeat(lambda x: x**2,2,3)
256
>>> repeat(os.path.dirname,'/home/kommusoft/testfolder/sqldump', 2)
'/home/kommusoft'

If you however plan to walk to the root of a directory, using a large number of repetitions is not safe: you never know that some user has made a cascade of over nine thousand directories.

like image 117
Willem Van Onsem Avatar answered Oct 22 '22 01:10

Willem Van Onsem