Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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)

like image 212
Aiden Amir Rafii Avatar asked Feb 01 '15 05:02

Aiden Amir Rafii


1 Answers

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
>>>
like image 81
taskinoor Avatar answered Oct 03 '22 02:10

taskinoor