Week 4: In-Class#
Coding Practice#
Code 4.1: Fish Population#
The fish population in a lake is influenced by two factors: natural growth, which increases the population, and fishing, which decreases it. Natural growth causes the population to increase by 25% each year. Fishing is regulated by the local authorities, who issue 1000 licenses annually. Therefore, the population of fish in the lake is modeled as
where \(N_{\text{old}}\) is the population of fish in the lake last year, and \(N_{\text{new}}\) is the population of fish in the lake this year.
If the initial fish population is 15000, we want to determine how the population in the lake changes over the following years. For simplicity, ignore the fact that the population of fish cannot be a decimal number.
Pen & Paper
Using the model above, and assuming an initial population of 15000 fish, calculate the population for each of the next 5 years. You may do the calculations with a calculator, or use Python as a calculator.
Demo
Write a script that prints the population of fish in the lake for the next 10 years. Start your script by defining the growth parameter, the initial population, and the number of licenses.
r = 0.25
population = 15000
licenses = 1000
Try increasing the number of licenses to see how many fish can be caught for the population to continue growing each year.
Code 4.2: Candy Exchange#
The owner of a candy shop came up with a plan to reduce the littering in front of the shop: “Bring back five candy wrappers, and get one candy for free!” This raises a question: If you start with a certain number of candies, how many candies can you actually end up eating? Assume that you keep returning wrappers as long as possible.
Pen & Paper
You should answer the question above for three different starting amounts of candy. Begin with a small starting number (for example, between 10 and 20), then try a larger number, and finally use a number greater than 100.
Demo
Write code which from the number of candies you have, computes the number of candies you can end up eating.
Code 4.3: Printing Song Lyrics#
The lyrics to the song “Around the World” by Daft Punk consists of the line "Around the world, around the world"
repeated 72 times. Write a script to print the lyrics of the song.
The first two lines of the output should look like this:
Around the world, around the world
Around the world, around the world
Hint
Start with the for-loop-statement for i in range(72):
Code 4.4: Printing Numbers#
First, write a for-loop that prints all the numbers from 1 to 20, each on its own line. Now, change your code such that it that constructs a string with all the numbers up to 20, separated by spaces. After the loop is finished the code should print the string. The output should look like:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
Hint
Look back at Prep 4.5: Collecting Values, where we start with the empty string ""
and keep adding text to it.
Finally, change you for-loop into a while-loop and produce the same output.
Hint
You now need a variable defined before the loop, e.g. n
, i
or count
(or a different name of your choice) that counts up. The counting variable should be defined before the loop and updated inside the loop.
Code 4.5: Sum of Numbers#
Sum the natural numbers from 1 up to n
using a for loop. The integer variable n
should be defined above your loop. For n = 5
, your code should print the following:
The sum of natural numbers up to 5 is 15
Hint
For this exercise, look back at Prep 4.5: Collecting Values. Define my_sum = 0
before the loop and update it inside the loop body. Then print the final sum in a string after the loop.
Run the code for n
set to 10
, 15
, 33
, and 42
and verify that you solution still produces the correct result.
Now, construct the code which, given the value of n = 5
, creates a and prints the following string:
1 + 2 + 3 + 4 + 5 = 15
The code should work for any value of n
.
Hint
For this exercise, look back at Prep 4.5: Collecting Values. We suggest that you copy the code from the preparation and keep modifying it until you get the desired output:
First, modify the range of the for loop such that the string is
1 2 3 4 5
.Now, modify the reassignment inside the loop such that the string is
1 + 2 + 3 + 4 + 5 +
.Now, modify the stop value in the range such that the string is
1 + 2 + 3 + 4 +
.Now, add a line of code after the loop such that the string becomes
1 + 2 + 3 + 4 + 5 =
.Finally, add the total sum to the string, which you computed in the first part of the exercise, such that the output is
1 + 2 + 3 + 4 + 5 = 15
.Optionally, look at your code and see if you can combine some of the reassignments to make your code more compact.
Code 4.6: Factorial (Buddy-Exercise)#
The factorial of a positive integer \(n\), denoted \(n!\), is defined as:
You are preparing educational material for a math class, and you want to show some examples of factorials. For this, you need a script that, given a positive integer n
, prints all the factorials from 1
to n
, including both the expression, calculations and the results.
Below are two scripts attempting to solve the problem. Agree with your buddy which script should each of you focus on.
Try each script. Does it produce the correct output? Analyze the code and figure out, how the code work. Explain the code to your buddy. Discuss the differences between the two scripts.
n = 5
fact_str = ""
solution = 1
for i in range(1, n + 1):
fact_str = fact_str + str(i)
solution = solution * i
print(str(i) + "! =", fact_str, "=", solution)
fact_str = fact_str + " * "
n = 5
for i in range(1, n + 1):
fact_str = str(i) + "! = 1"
solution = 1
for j in range(2, i +1 ):
fact_str = fact_str + " * " + str(j)
solution = solution * j
print(fact_str + " = " + str(solution))
Code 4.7: Printing a Pyramid#
In this exercise, you should write a program that prints a pyramid of a desired height using *
. For example, for height = 5
, the output should look like this:
*
***
*****
*******
*********
Hint
Notice that for height = 5
, you need to create two sequences. One is for the number of stars in each row, which is \(1, 3, 5, 7, 9\). The other is for the number of spaces in front, which is \(4, 3, 2, 1, 0\). Make an appropriate for-loop which prints:
4 1
3 3
2 5
1 7
0 9
Now it is easy to construct the lines with spaces and stars using string repetition and concatenation operators, as we did in the second week of the course.
For a hint to produce the first sequence, look back at Prep 4.4: Using the Iteration Variable.
Problem Solving#
Problem 4.8: Radioactive Decay#
You are modeling the decay of a lump of radioactive material. After each hour, 90% of the material remains.
Write a script that prints the amount of material remaining after \(1, 2, 3, ..., 10\) hours, given an initial amount. Start your script by defining the fraction of material remaining, and the initial amount as shown below.
R = 0.9 # remaining fraction after each hour
amount = 2.5
The first three lines of the output should look like the one below.
The amount left after 1 hours is 2.25
The amount left after 2 hours is 2.025
The amount left after 3 hours is 1.8225
Problem 4.9: Half-Life#
Each hour, 90% of the radioactive material remains. You would like to know how long it takes for the amount of material to fall below half of the initial amount.
Write a script that prints the amount of material remaining each hour until it is less than half of the initial amount. When that happens, the script should also print how many hours it took to reach that point. Your script should work correctly for any initial amount of material and for any valid remaining fraction.
For example, a script starting with
R = 0.75
amount = 6.5
should print the following.
The amount left after 1 hours is 4.875
The amount left after 2 hours is 3.65625
The amount left after 3 hours is 2.7421875
The amount is below half after 3 hours
Problem 4.10: Collatz Conjecture#
The Collatz conjecture is an unsolved problem in mathematics. One step of the Collatz conjecture is defined as:
The conjecture states that for any positive integer \(n\), the sequence \(n, \, f(n), \, f(f(n)), \, f(f(f(n))), \, \ldots\) will eventually reach the number 1. However, whether the conjecture is true has not yet been proven or disproven. You should write a script that counts the number of steps required to reach the number 1 from a given positive integer \(n\).
Consider starting with n = 3
. Since \(3\) is an odd number, the next number in the sequence is \(3 \cdot 3 + 1=10\). This is an even number, so the next number in the sequence is \(10/2=5\). The full sequence is \(3, 10, 5, 16, 8, 4, 2, 1\), and it took 7 steps to reach the number 1. You should print a message like the one below:
Stopped after 7 steps
Test your code with n = 27
, which should stop after 111 steps, and and n = 127
, which should stop after 46 steps.
Hint
Remember, that the modulo operator (%
) gives the remainder after division. This can be used to test whether numbers are odd or even, since even numbers are divisible by 2.
Problem 4.11: Rabbit Population#
We assume that a baby rabbit becomes a child after 1 month, and a child rabbit becomes an adult after 1 month. Each adult produces \(k\) baby rabbits every month. (Equivalently, each pair of adults produces \(2k\) baby rabbits.)
The population changes from one month to the next according to the following rules:
Here, \(A_t\) is the number of adult rabbits at month \(t\), \(C_t\) is the number of child rabbits, \(B_t\) is the number of baby rabbits, and \(k\) is the number of babies produced by each adult.
Write a script that computes the numbers of adult, child, and baby rabbits for 12 months. The script should begin with the code below:
adult = 0
child = 0
baby = 2
k = 3
The script should print the number of adult, child, and baby rabbits for each month. The first lines of the printout should look like this:
Month 1 : 0 baby, 2 child, 0 adult
Month 2 : 0 baby, 0 child, 2 adult
Month 3 : 6 baby, 0 child, 2 adult
Month 4 : 6 baby, 6 child, 2 adult
Month 5 : 6 baby, 6 child, 8 adult
Hint
Notice that all the new values depend on the old values. If you overwrite one value, you will not be able to compute the other new values correctly. You can use other variable names to store the new values. Then make a reassignment so that the new values are used as the old values in the next iteration.
Problem 4.12: Debt#
You have taken a loan with a certain monthly interest rate, and you are going to pay it back with a fixed monthly payment. Every month, the debt is computed by first adding the interest to the debt, and then subtracting the monthly payment. For example, if the debt is 20000 kr, the monthly interest rate is 5%, and the monthly payment is 2000 kr, the debt after the first month can be calculated as:
If, after interest is added, the debt is smaller than the monthly payment, only the remaining debt should be paid. For example, if at some point the debt becomes 1000 kr after adding interest, we have:
which is smaller than the monthly payment. Then, only the remaining debt is paid, and the debt is paid off.
We want to compute how long it takes to pay off a debt and how much you will pay in total. Write a script that starts by defining the parameters below.
debt = 20000 # Initial debt amount in kr
monthly_payment = 2000 # Fixed monthly payment amount in kr
interest_rate = 0.05 # 5% interest rate per month
For each month:
Compute the interest, which is the product of the interest rate and debt. Then, add the interest to the debt.
Determine whether the whole debt can be paid off this month. If not, pay the monthly payment. Otherwise, pay the remaining debt.
As you do the calculations, keep track of the total amount paid and the number of months. Finally, you should print the total amount paid and the time it took to pay off the debt. You don’t need to round any values, but you may print the amounts rounded to two decimal places. With the parameters above, the result should look like this:
Debt paid after 15 months.
Total payment 28421.44 kr.
Problem 4.13: Number of Windows#
You are now a construction engineer, and you need to order windows for a street of 11 newly built houses. The municipality has designed a peculiar street where all houses are one-story tall and have square ground plans. However, their side lengths increase by one meter for each house further down the street. The first house has a side length of 20 meters, the second 21 meters, and so on until the last house, which has a side length of 30 meters.
On each side of each house, you want to place as many windows as possible in one horizontal row. Each window is 1.5 meters wide, and windows can start directly at a corner, but there should be at least 1 meter of space between each window. For example, if the side is 8 meters long, you could place the first window in the corner and then have two more windows with 1 meter of space between them. This gives \(1.5 + 1 + 1.5 + 1 + 1.5 + 1 = 7.5\), leaving no space for another window. If the side is 9 meters long, you could place 4 windows corner to corner.
Write code that prints the number of windows needed for each building. Finally, the code should print the total number of windows for the entire street.
You will need the following variables:
window_width = 1.5
window_spacing = 1
minimum_side_length = 20
maximum_side_length = 30
The printed output for a street with only 4 houses (i.e., maximum_side_length = 23
) should look like this:
We need 32 windows for a house with side length 20
We need 32 windows for a house with side length 21
We need 36 windows for a house with side length 22
We need 36 windows for a house with side length 23
We need 136 windows in total
Problem 4.14: Pythagorean Triples#
A Pythagorean triple is a set of three positive integers \(a\), \(b\), and \(c\) such that \(a^2 + b^2 = c^2\). For example, \(3^2 + 4^2 = 5^2\). Given a maximum search variable n_search_max
, write a script that finds all Pythagorean triples where \(a\), \(b\), and \(c\) are all less than or equal to n_search_max
. You should avoid printing duplicates, for instance (3, 4, 5) and (4, 3, 5) should be considered the same triple.
For n_search_max = 20
, your output should look like this:
3 4 5 is a Pythagorean triple
6 8 10 is a Pythagorean triple
5 12 13 is a Pythagorean triple
9 12 15 is a Pythagorean triple
8 15 17 is a Pythagorean triple
12 16 20 is a Pythagorean triple
Hint
You can use three nested loops to iterate over all possible combinations of \(a\), \(b\), and \(c\). To avoid duplicates, adjust the range of the inner loops. For example, if the outer loop is iterating over \(c\), the iteration of \(b\) should not go beyond \(c\).
Problem 4.15: Disease Simulation #
We investigate an SIR (susceptible, infectious, recovered) model for an infectious disease. The model is based on the following assumptions:
People can be in one of three states: susceptible \(S_t\), infectious \(I_t\), or recovered \(R_t\). These values change over time \(t\), but the total population size \(S_t + I_t + R_t\) remains constant.
The infection rate \(\beta\) determines how many susceptible people an infectious person will infect each day. The number of people becoming infectious each day is \(\beta S_t I_t\).
The recovery rate \(\gamma\) determines how many infectious people will recover each day. The number of people recovering each day is \(\gamma I_t\).
The model is:
Write a script that simulates the spread of a disease over 100 days. You should always start with a population where only one person is infectious, and the rest are susceptible. You shouldn’t round the calculations, but you should print the rounded values.
For example, try the following parameters:
population = 1000
infectious = 1
infection_rate = 0.0004
recovery_rate = 0.2
days = 100
Print the number of susceptible, infectious, and recovered people every tenth day. The first few lines of the output should look like this:
Day 10, Susceptible: 989, Infectious: 6, Recovered: 5
Day 20, Susceptible: 930, Infectious: 34, Recovered: 36
Day 30, Susceptible: 699, Infectious: 125, Recovered: 176
Problem 4.16: Which Tetrahedral #
The \(n^\text{th}\) tetrahedral number is given by
and a sequence of tetrahedral numbers is
For an integer \(t\), you are interested in knowing whether \(t\) is a tetrahedral number, and if so, which number in the sequence it is. Write a script that finds the \(n\) such that \(T_n = t\) for a given \(t\). If \(t\) is not a tetrahedral number, the script should print that \(t\) is not a tetrahedral number.
For example, the script starting with t = 121
should print:
121 is not a tetrahedral number
Given other starting values, your script should print the following:
171700 is a tetrahedral number with n = 100
227920 is a tetrahedral number with n = 110
222439000 is not a tetrahedral number