CS61A(7): Function Examples

This is the lecture note of CS61A - Lecture 7.

Exam Preview

Question 4: Implementing Function

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
def remove(n, digit):
"""Return all digits of non-negative N
that are not DIGIT, for some
non-negative DIGIT less than 10.

>>> remove(231, 3)
21
>>> remove(243132, 2)
4313
"""
kept, digits = 0, 0
while ____________________:
n, last = n // 10, n % 10
if ___________________:
kept = ___________
digits = _________
return ___________________

Try it for yourself before looking at the answer.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
# ANSWER

def remove(n, digit):
"""Return all digits of non-negative N
that are not DIGIT, for some
non-negative DIGIT less than 10.

>>> remove(231, 3)
21
>>> remove(243132, 2)
4313
"""
kept, digits = 0, 0
while n > 0:
n, last = n // 10, n % 10
if last != digit:
kept = kept + 10 ** digits *last
digits = digits + 1
return kept

Decorators

Let's look at an example.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
def trace(fn):
def wrapped(x):
print('-> ', fn, '(', x, ')')
return fn(x)
return wrapped


def triple(x):
"""
>>> trace(triple)(12)
-> <function triple at 0x7fb70c45f048> ( 12 )
36
"""
return 3 * x

trace() is a HOF. We have already learnt HOFs, so it's easy for us to understand the code.

However, if a programmer doesn't know HOFs, he/she won't understand the code. For those programmers who know nothing about HOFs, Python provides special syntax to apply higher-order functions as part of executing a def statement, called a decorator.

1
2
3
4
5
6
7
8
@trace
def triple(x):
"""
>>> triple(12)
-> <function triple at 0x102a39848> ( 12 )
36
"""
return 3 * x

The annotation @trace affects the execution rule of def.

The function triple will be created as usual. however, the name triple is not bound to this function body. Instead, it is bound to the returned function value of calling trace on the newly defined triple function, i.e. triple = trace(triple).