Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Stumped by one line of Python

I'm unofficially doing a python course CS61A through Berkely, and I'm absolutely stumped by one simple assignment that 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've tried everything to make this work. It seems to me that this return stmt should do it:

return reduce(compose1, range(n))

But I'm not even close. Compose1 takes two args (f, g) and these should both be functions. But when the return statement calls 'compose1', 'compose1' uses '0' for 'f' and 'n' for 'g.' But 'f' and 'g' should be the function called--'square'

What am I missing.

like image 240
Dominique LaCasse Avatar asked Feb 23 '13 20:02

Dominique LaCasse


1 Answers

Here's a hint. Think about what the return value of compose1(square, square) would be.

like image 73
chepner Avatar answered Oct 11 '22 18:10

chepner