Voluntary homework

Generic badge Open this in Colab

The following exercises are voluntary and cover the content of the first part of this course. All exercises are considered to be solved in the Spyder editor in separate scripts.

Exercise 1 (“starter”)

As a “starter”, please play around with the following operators in the Spyder console. Apply the operators to numbers directly, but also work with variables.

Operator Description
+, -, *, / addition, subtraction, multiplication, division
// integer division
% modulo (“rest“ of a division)
-x, +x sign
** exponentiation
Operator Description
<, >, <=, >= comparison operators is smaller/equal? bigger/equal?
== comparison operator is equal?
!= comparison operator is not equal?
or, and, not boolean comparison operators
in is element of?

Exercise 2 (lists)

  1. Create two lists A and B, with A containing the numbers 7, 8, 9, and B containing the numbers 17, 18, 19.
  2. Apply to the second element of A and the third element of B some of the operators listed above.
  3. Use the built-in Python command sum() to calculate and print the sum of Aand B, respectively.
# example solution output:

sum of A: 24 sum of B: 54

Toggle solution
# Solution 2:
A = [  7,  8,  9]
B = [ 17, 18, 19]
print(f"sum of A: {sum(A)}")
print(f"sum of B: {sum(B)}")

Exercise 3 (using the script)

In this exercise we recap Chapter 7: for loops and train the scripting with the Spyder editor.

  1. In the Spyder editor, create a new Python script, e.g., called for_loops.py.
  2. Transfer your or the given solution of Exercise 1 into that script. Put the solution into its own cell.
  3. Do the same for Exercise 2 and the “Example with enumerate command” of Section 3 The enumerate function.
  4. Run your script at once and each cell individually.

Exercise 4 (dictionaries)

  1. Create a new script in the Spyder editor.
  2. Define the dictionary mouse as presented in Chapter 4 Variables.
  3. Expand mouse by the new key “owner”. Set as value your name.
    Note: You don’t have to redefine the entire dictionary. You can add any new entry by mouse["new key"]=value.
  4. Add another entry “blood pressure” with values 80, 75, 95, 180.
  5. Instead of printing out the value of each key manually, write a for-loop, that iterates over all keys and prints out the corresponding value.
    Hint: With mouse.keys() you get an iterable list of all keys (=sequence).
  6. Create a mouse2 dictionary by performing the same steps as in 1. This time, set the age to 38, the ID to 38979 and the weight to 37. Calculate the average age of both mice.
# example solution output:

SOLUTION 4.2-4.3:
{'ID': 45768,
'MWM_scores': [59, 50, 40, 27, 14, 11],
'age': 42,
'owner': 'My Name is Fabrizio',
'sex': 'male',
'weight': 36}

SOLUTION 4.4:
{'ID': 45768,
'MWM_scores': [59, 50, 40, 27, 14, 11],
'age': 42,
'blood pressure': [80, 75, 95, 180],
'owner': 'My Name is Fabrizio',
'sex': 'male',
'weight': 36}

SOLUTION 4.5:
ID: 45768
age: 42
sex: male
weight: 36
MWM_scores: [59, 50, 40, 27, 14, 11]
owner: My Name is Fabrizio
blood pressure: [80, 75, 95, 180]

SOLUTION 4.6:
40.0

Toggle solution
from pprint import pprint as pprint
# %% SOLUTION 4.2-4.3
# mouse-dictionary from the lecture:
mouse = {'ID': 45768,
         'age': 42,
         'sex': "male",
         'weight': 36,
         'MWM_scores': [59, 50, 40, 27, 14, 11]}
mouse['owner'] = 'My Name is Fabrizio'
print(f"SOLUTION 4.2-4.3:")
pprint(mouse)

# %% SOLUTION 4.4
mouse['blood pressure'] = [80, 75, 95, 180]
print(f"\nSOLUTION 4.4:")
pprint(mouse)
    
# %% SOLUTION 4.5
print(f"\nSOLUTION 4.5:")
for key in mouse.keys():
    print(f"{key}: {mouse[key]}")
    
# %% SOLUTION 4.6
mouse2 = {'ID': 38979,
          'age': 38,
          'sex': 'male',
          'weight': 37,
          'MWM_scores': [59, 40, 27, 14, 11]}
print(f"\nSOLUTION 4.6:")
print((mouse['age'] + mouse2['age'])/2)

Exercise 5 (for-loops and if-statements)

Given the list agents=["James Bond (007)", "Austin Powers (007)", "Hubert Bonisseur, (117)"], write a for-loop, that iterates over each of its elements and checks, if the current agent has a 007-license. Again, create a new Spyder script with an appropriate name for your solution.

# example solution output:

James Bond (007)
match! James Bond (007) has a 007 license.
Austin Powers (007)
match! Austin Powers (007) has a 007 license.
Hubert Bonisseur, (117)
warning! Hubert Bonisseur, (117) has no 007 license!

Toggle solution
# Solution 5
my_agents_list=["James Bond (007)", "Austin Powers (007)", 
        "Hubert Bonisseur, (117)"]
string_to_check = "007"
for current_agent in my_agents_list:
    print(current_agent)
    if string_to_check in current_agent:
        print(f"match! {current_agent} has a "
              f"{string_to_check} license.")
    else:
        print(f"warning! {current_agent} has "
              f"no {string_to_check} license!")

Exercise 6 (for-loops and the enumerate function)

Chapter 5 for loops contains a section about creating a for-loop via the enumerate function.

  1. Please, read this section.
  2. Create a new script in the Spyder editor.
  3. Create a number list number_list that ranges from 3 to 13 in the step-size of 1.
    Hint: Use the range() and list() command.
  4. Write a for-loop, that iterates over number_list and prints out each element entry-by-entry and its accoriding index, by using the enumerate function.
# example solution output:

number_list: [3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
the length of number_list: 10

index 0 has the value 3
index 1 has the value 4
index 2 has the value 5
index 3 has the value 6
index 4 has the value 7
index 5 has the value 8
index 6 has the value 9
index 7 has the value 10
index 8 has the value 11
index 9 has the value 12

Toggle solution
# Solution 6:
number_list = list(range(3,13,1))
print(f"number_list: {number_list}")
print(f"the length of number_list: {len(number_list)}")
print("")

for counter, value in enumerate(number_list):
    print(f"index {counter} has the value {value}")

Exercise 7 (for-loops and lists)

  1. Create a new script in the Spyder editor.
  2. Define the two lists:
    A = [101, 102, 103, 104]
    B = [ 10,  12,  13,  14]
    
  3. Write a for-loop that iterates over the range of the length of one of the two lists. Inside the loop, print out the iterative result of the element-by-element multiplication of A and B.
# example solution output:

i=0: A_i*B_i = 1010
i=1: A_i*B_i = 1224
i=2: A_i*B_i = 1339
i=3: A_i*B_i = 1456

Toggle solution
# Solution 7:
A = [101, 102, 103, 104]
B = [ 10,  12,  13,  14]

for i in range(len(A)):
    print(f"i={i}: A_i*B_i = {A[i] * B[i]}")

Exercise 8 (for-loops)

Given the list number_list_1=[4, 8, 12, 16, 20, 24, 28, 32], write in new Spyder script that prints out only elements of number_list_1 at even index positions.

# example solution output:

index: 0 (even) --> number 4
index: 2 (even) --> number 12
index: 4 (even) --> number 20
index: 6 (even) --> number 28

Toggle solution
# Solution 8:
number_list_1=[4, 8, 12, 16, 20, 24, 28, 32]
N = len(number_list_1)
for index in range(0,N,2):
    print(f"index: {index} (even) --> number {number_list_1[index]}")

Exercise 9 (functions)

Write a function print_name, that prints out a given input name.

# example solution output:

The input name is: Fabrizio.

Toggle solution
# Solution 9:
def print_name(string):
    print(f"The input name is: {string}.")
print_name(string="Fabrizio")

Exercise 10 (functions)

Given the list number_list_0=[4, 8, 3, 9], write a function my_average(input_list) (again, in a new script), that calculates and prints its average

\[\mu = \frac{1}{N} \sum_{i=1}^N x_i\]

with $x_i$ the individual elements of number_list_0.

Hints:

  • Use the len() command to determine the number of elements ($N$);
  • To calculate the sum, use a for-loop; within the for-loop, update a dummy sum variable (e.g., sum_runner) for every iteration (e.g., sum_runner = sum_runner + "new_value"); if you want to use this approach, you have to pre-initialize sum_runner = 0 before the loop.
# example solution output:

mean: 6.0

Toggle solution
# Solution 10:
number_list_0 = [4, 8, 3, 9]

def my_average(input_list):
    N  = len(input_list)
    sum_runner = 0
    for i in range(N):
        sum_runner +=  input_list[i]
        # this is similar to: 
        # sum_runner = sum_runner + number_list_0[i]

    mu = sum_runner/N
    print(f"mean: {mu}")

my_average(number_list_0)

Exercise 11 (functions)

Write a function product, that multiplies all numbers of a given number list. Apply your function to the list list1=[4, 8, 12, 16, 20, 32, 28, 24, -1].

# example solution output:

2642411520

Toggle solution
# Solution 11:
def product(inputlist):
    """Calculates the product of a given number-list"""
    result = 1 # we need an initialization of the later 
               # result variable
    for index in range(0, len(inputlist)):
        result = result * inputlist[index]
    return result

list1=[4, 8, 12, 16, 20, 32, 28, -24, -1]
print(product(list1))

Exercise 12 (functions)

Write a function calc_max, that finds the maximum value and it index of a given list. Apply your function to the list defined in Exercise 11.

# example solution output:

the maximum of [4, 8, 12, 16, 20, 32, 28, -24, -1] is 32 at index 5

Toggle solution
# Solution 12:
list1=[4, 8, 12, 16, 20, 32, 28, -24, -1]
def calc_max(inputlist):
    current_max = inputlist[0]
    index_of_max = 0
    for index in range(1,len(inputlist)):
        if inputlist[index] > current_max:
            current_max = inputlist[index]
            index_of_max = index
    return current_max, index_of_max

maximum, maximum_index =  calc_max(inputlist = list1)
print(f"the maximum of {list1} is {maximum} at index {maximum_index}")

Exercise 13 (deep vs. shallow copy)

  1. Given the list A = [9, 27, 1, 8, 77]. Create a copy of A into a new variable called B. Change the 3rd entry of A to -80 and print out both, A and B. What do you notice?
  2. Please read the chapter about deep vs. shallow copy and apply appropriate changes to your script, so that a change of an element of A will no longer affect the entries in B. Verify your adjustments by, again, changing the 3rd entry of A to -80 and printing out B (that now should still show the initial defintion of A).
# example solution output:

initial A: [9, 27, 1, 8, 77]
created B: [9, 27, 1, 8, 77]
A after modifying A: [9, 27, -80, 8, 77]
B after modifying A: [9, 27, -80, 8, 77]

After applying appropriate changes:
initial A: [9, 27, 1, 8, 77]
created B: [9, 27, 1, 8, 77]
A after modifying A: [9, 27, -80, 8, 77]
B after modifying A: [9, 27, 1, 8, 77]

Toggle solution
# Solution 13:
from copy import deepcopy
A = [9, 27, 1, 8, 77]
print(f"initial A: {A}")
B = deepcopy(A)
print(f"created B: {B}")
A[2] = -80
print(f"A after modifying A: {A}")
print(f"B after modifying A: {B}")



The following exercises cover the content of part 2 of this course and can be voluntarily solved after the course’ end.

Exercise 14 (data I/O)

  1. Please visit this cheat sheet on Python Data I/O function and read the section about Built-in Python I/O functions.
  2. Write a script, that generates a new text file in write mode (w).
  3. Iterate over the number 0 to 10 and write them line-by-line into the newly created file.
    Hint: Use the str() command to convert an integer (or float) number into a string (if necessary). Also, use \n within the print() command to force a line break after each entry input.
  4. Save your results appropriately by closing the newly generate text file.
  5. Re-open the text file in read mode (r).
  6. Write a for loop, that iterates over each line within the text file and prints out each individual entry.
  7. Don’t forget to close your file at the end.
# example solution output:

0
1
2
3
4
5
6
7
8
9
10

Toggle solution
# Solution 14:
filename = 'my_data_file.txt'
file_object = open(filename, mode='w')
for i in range(11):
    file_object.write(f"{str(i)}\n")
file_object.close()

file_object = open(filename, mode='r')
N_lines = len(file_object.readlines())
file_object.seek(0) 
for line in range(N_lines):
    print(file_object.readline())
file_object.close()

Exercise 15 (NumPy)

Given the NumPy array A,

A = np.array([np.arange(0,3,1)]*5,dtype='float16'),

write a script that

  1. prints out its shape,
  2. prints out all entries of column 1 and 2, separately and at once,
  3. overwrites the values of column 1 by the sum of the values of columns 2 and 3,
  4. replaces the entry of row 1, column 3 with its exponentiation with the factor 2,
    Hint: x**2.
  5. replaces the entry of row 2, column 3 with the square root of the entry of row 2, column 0,
    Hint: Please find the NumPy function for calculating the square root in the Useful NumPy functions list of Chapter 10: NumPy - Our data container.
  6. prints out all entries with even index values of column 3, and
  7. calculates the average and standard deviation of all entries of column 3.
    Hint: Again, please find the appropriate NumPy functions in the Useful NumPy functions list.
# example solution output:

SOLUTION 15.1:
A:
[[0. 1. 2.]
[0. 1. 2.]
[0. 1. 2.]
[0. 1. 2.]
[0. 1. 2.]]
A.shape: (5, 3)

SOLUTION 15.2:
[0. 0. 0. 0. 0.]
[1. 1. 1. 1. 1.]
[[0. 1.]
[0. 1.]
[0. 1.]
[0. 1.]
[0. 1.]]

SOLUTION 15.3:
[[3. 1. 2.]
[3. 1. 2.]
[3. 1. 2.]
[3. 1. 2.]
[3. 1. 2.]]

SOLUTION 15.4 and 15.5:
4.0
1.732
[[3. 1. 4. ]
[3. 1. 1.732]
[3. 1. 2. ]
[3. 1. 2. ]
[3. 1. 2. ]]

SOLUTION 15.6:
[4. 2. 2.]

SOLUTION 15.7:
the result: 2.345703125 +/- 0.83349609375

Toggle solution
# %% SOLUTION 15.1
import numpy as np
A = np.array([np.arange(0,3,1)]*5,dtype='float16')
print(f"SOLUTION 15.1:")
print("A:")
print(A)
print(f"A.shape: {A.shape}\n")

# %% SOLUTION 15.2
print(f"SOLUTION 15.2:")
print(A[:, 0])
print(A[:, 1])
print(A[:, 0:2])
print("")

# %% SOLUTION 15.3
print(f"SOLUTION 15.3:")
A[:,0] = A[:,1] + A[:,2]
print(A)
print("")

# %% SOLUTION 15.4 and 15.5
print(f"SOLUTION 15.4 and 15.5:")
A[0,2] = A[0,2]**2
A[1,2] = np.sqrt(A[1,0])
print(A[0,2])
print(A[1,2])
print(A)
print("")

# %% SOLUTION 15.6
print(f"SOLUTION 15.6:")
print(A[0:5:2, 2]) # all entries with even index of column 3
print("")

# %% SOLUTION 15.7
print(f"SOLUTION 15.7:")
print(f"the result: {A[:,2].mean()} +/- {A[:,2].std()}")

updated: