Directed by a single line of Python

I am unofficially following the python CS61A course through Berkely, and I'm absolutely stumped by one simple assignment, which requires me to provide only one expression at the very end of the provided template. Here is the problem code:

# HW 4 Q5. (fall 2012)

def square(x):
    return x*x

def compose1(f, g):
    """Return a function of x that computes f(g(x))."""
    return lambda x: f(g(x))

from functools import reduce

def repeated(f, n):
    """Return the function that computes the nth application of f, for n>=1.

    f -- a function that takes one argument
    n -- a positive integer

    >>> repeated(square, 2)(5)
    625
    >>> repeated(square, 4)(5)
    152587890625
    """
    assert type(n) == int and n > 0, "Bad n"
    return reduce(compose1, "*** YOUR CODE HERE ***" )

repeated(square, 2)(5) # Sample run

I tried everything to make this work. It seems to me that this return should do this:

return reduce(compose1, range(n))

But I'm not even close. Compose1 takes two arguments (f, g), and they must be functions. But when the return statement calls "compose1", "compose1" uses "0" for "f" and "n" for "g". But 'f' and 'g' must be a function called - squared

What am I missing.

+5
source share
3 answers

reduce , : . , [f] return reduce(compose1, [f]), f.

compose1 . [f, f] :

  compose(f, f)
= lambda x: f(f(x))

. , [f, f, f], :

  compose(compose(f, f), f)
= lambda x: f(f(f(x)))

. f . [f] * n, n times f.

+1

. , compose1(square, square).

+5

Compose ,

Using range, you pass a compse1pair of integers (which rightfully explode because they intcannot be called. You want to pass a list of functions that you want to create.

reducecalls its first argument in the first two elements of its second argument, then for that result and the third element ... until you reach the end. Intermediate results will look like this:

compose1(f1, f2)
compose1(compose(f1, f2), f3)
compase1(compose1(compose(f1, f2), f3), f4)
....

or more compact

 f1(f2(x))
 f1(f2(f3(x)))
 f1(f2(f3(f4(x))))
 ....
0
source

All Articles