
Week2 of CS61A
In the week2, I will learn 3. Control and 4. Higher-Order Functions . In sum, my mission is that Disc01, HW02 and Hog(project) .
3. Control
I feel too easy for me.
Just Conditional and While Statement.
And Pure function.
Pure functions have no side effects—they only accept inputs and produce outputs.
4. Higher-Order Functions
I feel it just summation.
And higher-order function.
Yay, I meet some programming that I think it is awesome.
def make_repeater(f, n):
"""Returns the function that computes the nth application of f.
>>> add_three = make_repeater(increment, 3)
>>> add_three(5)
8
>>> make_repeater(triple, 5)(1) # 3 * (3 * (3 * (3 * (3 * 1))))
243
>>> make_repeater(square, 2)(5) # square(square(5))
625
>>> make_repeater(square, 3)(5) # square(square(square(5)))
390625
"""
"*** YOUR CODE HERE ***"
def repeater(x):
for _ in range(n):
x = f(x)
return x
return repeaterdef make_averaged(original_function, times_called=1000):
"""Return a function that returns the average value of ORIGINAL_FUNCTION
called TIMES_CALLED times.
To implement this function, you will have to use *args syntax.
>>> dice = make_test_dice(4, 2, 5, 1)
>>> averaged_dice = make_averaged(roll_dice, 40)
>>> averaged_dice(1, dice) # The avg of 10 4's, 10 2's, 10 5's, and 10 1's
3.0
"""
# BEGIN PROBLEM 8
"*** YOUR CODE HERE ***"
def averaged_function(*args):
total = 0
for _ in range(times_called):
total = total + original_function(*args)
return total / times_called
return averaged_function
# END PROBLEM 8
The project hog is so easy.
I don't want to talk about any more.