In-Class#
Coding Practice#
Code 4.1: Print Song Lyrics#
The song “Around the World” by Daft Punk consists of the lyrics "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
You only need 2 lines of code to print the lyrics.
Code 4.2: Printing Numbers#
Write some code that prints all the numbers from 1 to 20, each on its own line.
Now, write a script that constructs a string with all the numbers up to 20, that is, the string:
"1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 "
.
After the loop, print this string to get all numbers printed on a single line.
Hint
Look back at Prep 4.5: Collecting Values, where we start with the empty string ""
and keep adding text to it.
Code 4.3: Sum of Numbers#
Sum the numbers from 1 up to and including \(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 numbers up to 5 is 15
Run the code for n
set to 10
, 15
, 33
, and 42
.
Now, construct the code which, given the value of n = 5
, creates a string that when printed gives the following output:
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 text is
1 2 3 4 5
.Now, modify the reassignment inside the loop such that the text is
1 + 2 + 3 + 4 + 5 +
.Now, modify the stop value in the range such that the text is
1 + 2 + 3 + 4 +
.Now, add a line of code after the loop such that the text is
1 + 2 + 3 + 4 + 5 =
.Finally, compute the sum of numbers. Define
my_sum = 0
before the loop and update it inside the loop body. Also, remember to add the last value tomy_sum
and check that the value is correct.Now, add the final reassignment of the text 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.4: Geometric Cake#
We have baked a cake, and each day you eat half of what is left. Write a script that prints how much of the cake is left each day in percentage. If less than 1% (min_cake = 0.01
) of the cake remains, the printing should stop, and nothing further should be printed.
The first 3 lines of the output should look like this:
There is 50.0 % cake left on day 1
There is 25.0 % cake left on day 2
There is 12.5 % cake left on day 3
The code should work for any amount of min_cake
Hint
Use a while-loop. Define two variables, cake
and day
, and use the value of cake
to construct the stopping condition. Inside the loop, update the values of cake
and day
, and print the output. Adjust the initial values of cake
and day
, the order of operations in the loop body, and the stopping condition until you get the desired output. You can also use break
to stop the loop.
Code 4.5: Printing the Multiplication Table#
Multiplication tables are great for teaching schoolchildren how to multiply. Below is the multiplication table for the numbers up to 5. You should now write code that prints the multiplication table for the numbers up to 10.
1 2 3 4 5
2 4 6 8 10
3 6 9 12 15
4 8 12 16 20
5 10 15 20 25
Hint
Here is a suggested approach for how to print the 10-table:
Similar to Prep 4.5: Collecting Values, write a for-loop that uses the iteration variable
i
to construct a string1 2 3 4 5 6 7 8 9 10
and print it outside the loop. You have now printed the first row of the table.Modify the code such that it prints any line of the table. For this, add a line
j = 3
at the beginning of the code and change the reassignment to use the product ofi
andj
instead ofi
. Now you can print the numbers from any line of the table by changing the variablej
. Confirm that this works as expected.Modify the line where
j
is defined so that it loops over values from 1 to 10. You will need to indent all other lines of the code to place them inside the loop body. Now you should be able to print the entire table.The final step is to make the printed numbers align nicely for numbers with up to three digits. To do this, add spaces before each number when constructing the string. First, try adding 2 spaces using
2 * " "
in front of each number. You need to add 2 spaces for single-digit numbers, and 1 space for two-digit numbers. In other words, add3 - len(str(i * j))
spaces. Confirm that this works as expected.
Code 4.6: Factorial#
The factorial of a number \(n\) is defined as:
Write code to print all the factorials from 1 to the integer \(n\) (including \(n\)). You should print both the calculation and the result. For n = 3
, the output should look like this:
1! = 1 = 1
2! = 1*2 = 2
3! = 1*2*3 = 6
Run your solution for n = 7
and n = 10
and check it against these values: 7! = 5040, 10! = 3628800.
Hint
You can write code to create one line, similar to the sum of numbers exercise. Your code should work for any j
. For example, for j = 4
, it should create the string 4! = 1*2*3*4 = 24
. Then, add an outer loop to create lines for all numbers up to n
, similar to the multiplication table.
As an extra challenge, try to make code that uses only one for-loop. For this, reuse the middle part of the line printed in the previous iteration. For the third line, reuse the part 1*2*3
, and construct the middle part of the fourth line by adding *4
to it.
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.
Code 4.8: Printing a Diamond#
Write a program that prints a diamond using *
. For height = 5
, the output should look like this:
*
***
*****
*******
*********
*******
*****
***
*
Hint
After the pyramid from the previous exercise is printed, add another for-loop which prints the bottom part of the diamond. The bottom part is inverted and one line shorter than the pyramid from the previous exercise.
Problem Solving#
Problem 4.9: Start of Radioactive Decay#
You have a lump of radioactive material that decays. The amount remaining after each hour is 90% of the amount from the previous hour. In other words, the amount of the material is multiplied by 0.9 every hour.
Write a script that, given the initial amount of material, prints the amount remaining after \(1, 2, 3, ..., 10\) hours. Start your script by defining the decay parameter and the initial amount as shown below.
R = 0.9
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.10: Radioactive Decay Half-time#
You would like to know how long it takes for the amount of radioactive material to fall below half of the initial amount. Modify your script from the previous problem to keep printing until the amount of material is less than half of the initial amount. When that happens, the script should 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 decay parameter.
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.11: Fish Population#
A lake has a population of fish that grows by 25% each year. The local authorities sell 1000 fishing licenses each year. Therefore, we model the population of fish in the lake 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.
Write a script that prints the population of fish in the lake for the next 10 years, ignoring the fact that the population of fish cannot be a decimal number. Start your script by defining the growth parameter, the initial population, and the number of licenses.
r = 0.25
population = 15000
licenses = 1000
The first three lines of the output should look like this:
The population after 1 years is 17750.0
The population after 2 years is 21187.5
The population after 3 years is 25484.375
Try increasing the number of licenses to see how many fish can be caught for the population to continue growing each year.
Problem 4.12: 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.
Problem 4.13: Rabbit Population#
We assume that baby rabbits reach child age after 1 month, and child rabbits reach adult age after 1 month. Each adult creates \(k\) baby rabbits every month. (Equivalently, we could say that each adult pair creates \(2k\) rabbits.) Therefore, we model the population growth of rabbits as:
Here, \(A_t\) is the number of adult rabbits at time \(t\), \(C_t\) is the number of child rabbits, \(B_t\) is the number of baby rabbits, and \(k\) is the number of baby rabbits each adult rabbit creates.
Write a script that computes the number of rabbits for 12 months. The script should start 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
For each month, first compute the new values from the old values. Then make a reassignment so that the new values are used as the old values in the next iteration.
Problem 4.14: 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.15: 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.16: 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\) is a Pythagorean triple. 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, e.g., (3, 4, 5) and (4, 3, 5) are 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.17: 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.18: 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