This is an archived version of the course and is no longer updated. Please find the latest version of the course on the main webpage.

Exercises - Functions

Now, over to you! Here are some lab exercises for you to practise your understanding of functions!

Many thanks to the following people for contributing to these exercises: Luca Grillotti

Function Implementation

Exercise 1

1.a

Implement a function sum_arguments(...) which sums all the elements passed as parameters.

For example, sum_arguments(2,5,7) should return 14, and sum_arguments(3) should return 3. sum_arguments() should return 0.

1.b

Suppose you have a list of numbers:

  • l_1=[1,2,3,4,5]
  • l_2=[6,7]

Try to guess and understand what the following python expressions do/print:

1.b.1
sum_arguments(l_1)
1.b.2
sum_arguments(*l_1)
1.b.3
sum_arguments(*l_1, *l_2)
1.b.4
x, *y, z = l_1
print(x, y, z)
1.b.5
x, *y, z = l_2
print(x, y, z)
1.b.5
x, *y, z = l_1, l_2
print(x, y, z)

Exercise 2

2.a

Implement a function show_animal_names(…) which prints the names of some animals passed as keyword arguments.

For example, show_animal_names(mouse=’Stuart’, cat=’Snowbell’, pig=’Babe’) should print:

The name of the mouse is Stuart
The name of the cat is Snowbell
The name of the pig is Babe

2.b

Consider 2 dictionaries:

d_1 = {'mouse': 'Stuart', 'dog': 'Chief'}
d_2 = {'pig': 'Babe', 'dog': 'Beethoven'}

Try to guess and understand what the following python expressions do/print:

2.b.1

d_3 = { d_1, d_2 }
print(d_3)

2.b.2 (merging dictionaries)

d_3 = { **d_1, **d_2 }
d_4 = { **d_2, **d_1 }
print(d_3)
print(d_4)

What do you notice?

This technique can be used for easily merging dictionaries. Be careful: as you’ve seen just above, if the dictionaries have some keys in common, some of the values will be erased.

2.b.3

show_animal_names(**d_1, **d_2)

Exercise 3

Consider the following Python function:

def f(x, l=[]):
    l.append(x)
    print(l)
    return l

Try to guess and understand what the following code does/shows:

f(1)
f(2)

What do you notice?

The reason why this is happening is that the list l is both mutable and a default argument. So each time l gets updated, the default argument gets updated with it!

A quick solution to this problem is to use None as a default argument for l:

def f(x, l=None):
    if l is None:
        l = []
    l.append(x)
    print(l)
    return l

Exercise 4 (Recursion)

Implement a recursive Python function to_flatten_list(l: list) which flattens any list into a 1-dimensional list.

For example, to_flatten_list([1, [2, 3, [4, 5], 6], [[7, [8]]], [[]]]) should return [1, 2, 3, 4, 5, 6, 7, 8]