Skip to content Skip to sidebar Skip to footer

Repeat Function Python

I'm stuck at higher-order functions in python. I need to write a repeat function repeat that applies the function f n times on a given argument x. For example, repeat(f, 3, x) is

Solution 1:

You have two problems:

  1. You are recursing the wrong number of times (if n == 1, the function should be called once); and
  2. You aren't calling f on the returned value from the recursive call, so the function is only ever applied once.

Try:

def repeat(f, n, x):
    if n == 1: # note 1, not 0returnf(x)
    else:
        returnf(repeat(f, n-1, x)) # call f with returned value

or, alternatively:

def repeat(f, n, x):
    if n == 0:
        return x # note x, not f(x)else:
        returnf(repeat(f, n-1, x)) # call f with returned value

(thanks to @Kevin for the latter, which supports n == 0).

Example:

>>>repeat(lambda z: z + 1, 2, 2)
4
>>>assert repeat(lambda z: z * 2, 4, 3) == 3 * 2 * 2 * 2 * 2>>>

Solution 2:

You've got a very simple error there, in the else block you are just passing x along without doing anything to it. Also you are applying x when n == 0, don't do that.

defrepeat(f,n,x):
    """
    >>> repeat(lambda x: x+1, 2, 0)
    2
    """return repeat(f, n-1, f(x)) if n > 0else x

Post a Comment for "Repeat Function Python"