# HW 02
# Q1: Product
def product(n, f):
sum = 1
while n:
sum *= f(n)
n -= 1
return sum
1
2
3
4
5
6
2
3
4
5
6
# Q2: Accumulate
注意运算次序,题目很简单!
while n > 0:
base = combiner(base, f(n))
n -= 1
return base
1
2
3
4
2
3
4
结果:
>>> accumulate(lambda x, y: 2 * (x + y), 2, 3, square)
106
# Error: expected
# 58
# but got
# 106
1
2
3
4
5
6
7
2
3
4
5
6
7
def summation_using_accumulate(n, f):
return accumulate(add,0,n,f)
1
2
2
def product_using_accumulate(n, f):
return accumulate(mul,1,n,f)
1
2
2
# Q3: Make Repeater
def make_repeater(h, n):
return accumulate(compose1,identity,n,lambda k:h)
1
2
2