Exercise Notebook 2 - Smart coding

Exercise Notebook 2 - Smart coding#

You can download this notebook and the additional files by clicking the download button() in the top right and selecting “Exercise notebook”.

Exercise 2.1.1

Calculate the area of a circle with a radius of \(4\) cm in the box below using the calculate_circle_area function.

### DO NOT CHANGE ANYTHING HERE ###

def calculate_circle_area(r):
    pi = 3.141592653589793
    area = pi*(r**2)
    return area

###################################


r = ...
circle_area = ...


print(circle_area)
Exercise 2.1.2

Add a description to the calculate_circle_area(r) function below, as a docstring, and check if the docstring appeared in it by using either ? or ??

def calculate_circle_area(r):
    '''PUT YOUR DOCSTRING HERE!'''
    pi_circle = 3.141592653589793
    area = pi_circle*(r**2)
    return area
(Fixing) Exercise 2.1.3

Below is a function that should calculate the water pressure in the sea, as a function of depth. But it isn't working. Can you spot the error and fix it? Do not change any other line except the line with the error.
def water_pressure(z):
    '''Calculates the water pressure in the sea at a depth of input z (meters). returns a value in Bar.'''
    
    water_density = 1000         #kg/m^3
g = 9.81                     #m/s^2
    p_atm = 100000               #Pa
    
    p_z = (p_atm + (z * water_density) * g) / 100000
    
    return p_z 

calculated_pressure = water_pressure(2000)
print(calculated_pressure)
Exercise 2.1.4

Write a function called k_e() to calculate the kinetic energy of some object. It should have mass and velocity as its arguments, in that order. In case you forgot, the kinetic energy equation is

\[E_k = \frac{mv^2}{2}\]
#write your funtion below
...
...


print(k_e(10, 5))
(Searching) Exercise 2.1.5

Use the print() and k_e() functions to print a nice formatted output for any arbitrary input. Example of a desired output: The kinetic energy is: 200 J
#write your code here
...
...
(Fixing) Exercise 2.1.6

The function below does not give the right answer. Could you fix it?
def add_two(numb):
    """
    add_two(numb) function -> takes the input numb and adds 2 to it
    
    Input:
        numb -> an integer, to which 2 must be added
    
    Output:
        ret -> a return integer, which is equal to numb + 2
    """
    ret = add_one(add_one(add_one(numb)))
    return ret

def add_one(number):
    """
    add_one(number) function -> takes the input number and adds 1 to it
    
    Input:
        number -> an integer, to which 1 must be added
    
    Output:
        ret -> a return integer, which is equal to number + 1
    """
    ret = number
    return ret


x = 5
y = add_two(x)

print(f'{x} + 2 is {y}, which is {y == x + 2}')
if y != x + 2:
    print('Something is wrong here...')
else:
    print('Looks gucci')
Exercise 2.3.1
One of the most crucial applications of if statements is filtering the data from errors and checking whether an error is within a certain limit.

For example, checking whether the difference between an estimated value and the actual value are within a certain range.

Mathematically speaking, this can be expressed as

\[|\hat{y} - y| < \epsilon\]

where \(\hat{y}\) is your estimated value, \(y\) is the actual value and \(\epsilon\) is a certain error threshold.

The function check_error_size() below must do the same — it should return True if the error is within the acceptable range eps and False if it is not.

Hint: the abs function is builtin.

def check_error_size(estimated_value, true_value, eps):
    ... # your if statement (error in acceptable range)
        return True
    ... # statement if not in acceptable range
        return False

#You can try to check it by yourself by running the function with some self-chosen numbers
print(check_error_size(0.5, 0.4, 0.2))

#Make your own tests below.
Exercise 2.3.2

Use the knowledge you have obtained in this Notebook and write your very own function to classify soil samples based on the average grain size. The classification you have to implement is the following:
  1. Clay: avg grain size \(<\) 0.002 mm

  2. Silt: 0.002 mm \(\leq\) avg grain size \(<\) 0.063 mm

  3. Sand: 0.063 mm \(\leq\) avg grain size \(<\) 2 mm

  4. Gravel: 2 mm \(\leq\) avg grain size \(<\) 63 mm

Your task is to write the function, which will return the name of the soil type based on the provided average grain size in millimeters.
def classify_soil(avg_grain_size):
    ...


print(classify_soil(1.5))
print(classify_soil(0.002))
print(classify_soil(4))
Exercise 2.3.3 — Triangle Inequality

Let's imagine that you received a request to manage a web-application, which provides and visualizes InSAR data of the estimated displacement in an area.

The app is already quite cool, however, there is always room for improvement. For example, one might want to look into the statistics over the area of a triangle.

Your goal is to help implement such functionality by checking whether the user selected a valid triangle. You need to do this by checking that the length of each of the sides is smaller than the sum of the other two (this condition is called the triangle inequality).
def check_triangle(side_a, side_b, side_c):
    ...


print(check_triangle(1, 2, 4)) # invalid
print(check_triangle(1, 2, 3)) # border-line (the triangle is flat) you may classify this as invalid
print(check_triangle(3, 4, 5)) # valid