Note: Click on "Kernel" > "Restart Kernel and Run All" in JupyterLab after finishing the exercises to ensure that your solution runs top to bottom without any errors. If you cannot run this file on your machine, you may want to open it in the cloud .
The exercises below assume that you have read the second part of Chapter 7.
The ...
's in the code cells indicate where you need to fill in code snippets. The number of ...
's within a code cell give you a rough idea of how many lines of code are needed to solve the task. You should not need to create any additional code cells for your final solution. However, you may want to use temporary code cells to try out some ideas.
Q1: Write a function nested_sum()
that takes a list
object as its argument, which contains other list
objects with numbers, and adds up the numbers! Use nested_numbers
below to test your function!
Hint: You need at least one for
-loop.
nested_numbers = [[1, 2, 3], [4], [5], [6, 7], [8], [9]]
def nested_sum(list_of_lists):
"""Add up numbers in nested lists.
Args:
list_of_lists (list): A list containing the lists with the numbers
Returns:
sum (int or float)
"""
...
...
...
return ...
nested_sum(nested_numbers)
Q2: Generalize nested_sum()
into a function mixed_sum()
that can process a "mixed" list
object, which contains numbers and other list
objects with numbers! Use mixed_numbers
below for testing!
Hints: Use the built-in isinstance() function to check how an element is to be processed.
mixed_numbers = [[1, 2, 3], 4, 5, [6, 7], 8, [9]]
import collections.abc as abc
def mixed_sum(list_of_lists_or_numbers):
"""Add up numbers in nested lists.
Args:
list_of_lists_or_numbers (list): A list containing both numbers and
lists with numbers
Returns:
sum (int or float)
"""
...
...
...
...
...
...
return ...
mixed_sum(mixed_numbers)
Q3.1: Write a function cum_sum()
that takes a list
object with numbers as its argument and returns a new list
object with the cumulative sums of these numbers! So, sum_up
below, [1, 2, 3, 4, 5]
, should return [1, 3, 6, 10, 15]
.
Hint: The idea behind is similar to the cumulative distribution function from statistics.
sum_up = [1, 2, 3, 4, 5]
def cum_sum(numbers):
"""Create the cumulative sums for some numbers.
Args:
numbers (list): A list with numbers for that the cumulative sums
are calculated
Returns:
cum_sums (list): A list with all the cumulative sums
"""
...
...
...
...
...
return ...
cum_sum(sum_up)
Q3.2: We should always make sure that our functions also work in corner cases. What happens if your implementation of cum_sum()
is called with an empty list []
? Make sure it handles that case without crashing! What would be a good return value in this corner case?
Hint: It is possible to write this without any extra input validation.
cum_sum([])
< your answer >