"""Submission for 61A Homework 2.
Name:
Login:
Collaborators:
"""
Q1
def product(n, term):
"""Return the product of the first n terms in the sequence formed
by applying term to the integers 1, ..., n.
term -- a function that takes one argument
"""
"*** YOUR CODE HERE ***"
result = 1
for i in range(1, n + 1):
result *= term(i)
return result
def factorial(n):
"""Return n factorial by calling product.
>>> factorial(4)
24
"""
"*** YOUR CODE HERE ***"
return product(n, lambda x: x)
def factorial_test():
assert factorial(4) == 24, "factorial(4) should be 24"
assert factorial(3) == 6, "factorial(3) should be 6"
assert factorial(5) == 120, "factorial(5) should be 120"
factorial_test()
Q2
def accumulate(combiner, start, n, term):
"""Return the result of combining the first n terms in a sequence.
*** YOUR DESCRIPTION HERE ***
"""
"*** YOUR CODE HERE ***"
result = start
for i in range(start, n+1):
result = combiner(result, term(i))
return result
def summation_using_accumulate(n, term):
"""An implementation of summation using accumulate."""
"*** YOUR CODE HERE ***"
return accumulate(lambda x, y : x + y, 0, n, term)
def summation_using_accumulate_test():
assert summation_using_accumulate(2, lambda x : x) == 3,
"summation_using_accumulate(2, lambda x : x) should be 3"
assert summation_using_accumulate(100, lambda x : x) == 5050,
"summation_using_accumulate(100, lambda x : x) should be 5050"
summation_using_accumulate_test()
def product_using_accumulate(n, term):
"""An implementation of product using accumulate."""
"*** YOUR CODE HERE ***"
return accumulate(lambda x, y : x * y, 1, n, term)
def product_using_accumulate_test():
assert product_using_accumulate(3, lambda x : x) == 6,
"product_using_accumulate(3, lambda x : x) should be 6"
assert product_using_accumulate(5, lambda x : x) == 120,
"product_using_accumulate(5, lambda x : x) should be 120"
product_using_accumulate_test()
Q3
def double(f):
"""Return a function that applies f twice.
f -- a function that takes one argument
"""
"*** YOUR CODE HERE ***"
return lambda x : f(f(x))
def double_test():
assert double(lambda x : x + 1)(3) == 5, "double(lambda x : x + 1)(3) should be 5"
assert double(lambda x : x * 2)(4) == 16, "double(lambda x : x * 2)(4) should be 16"
double_test()
Q4
def repeated(f, n):
"""Return the function that computes the nth application of f.
f -- a function that takes one argument
n -- a positive integer
>>> repeated(square, 2)(5)
625
"""
"*** YOUR CODE HERE ***"
def nthrepeated(x):
for i in range(n):
x = f(x)
return x
return nthrepeated
def square(x):
"""Return x squared."""
return x * x
def repeated_test():
assert repeated(square, 2)(5) == 625,
"repeated(square, 2)(5) should be 625"
assert repeated(square, 0)(5) == 5,
"repeated(square, 0)(5) should be 5"
assert repeated(square, 1)(5) == 25,
"repeated(square, 1)(5) should be 25"
repeated_test()
def compose1(f, g):
"""Return a function h, such that h(x) = f(g(x))."""
def h(x):
return f(g(x))
return h
网友评论