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

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.

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.

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

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

Code 4.6: Factorial#

The factorial of a number \(n\) is defined as:

\[ n! = 1 \cdot 2 \cdot 3 \cdot \dots \cdot (n-1) \cdot n .\]

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.

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:

    *
   ***
  *****
 *******
*********

Code 4.8: Printing a diamond#

Write a program that prints a diamond using *. For height = 5, the output should look like this:

    *
   ***
  *****
 *******
*********
 *******
  *****
   ***
    *

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:

\[ N_{\text{new}} = N_{\text{old}} + 0.25 N_{\text{old}} - 1000, \]

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:

\[\begin{split} f(n) = \begin{cases} n/2 & \text{if $n$ is even} \\ 3n+1 & \text{if $n$ is odd} \end{cases} \end{split}\]

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:

\[\begin{split} \begin{align} \nonumber A_{t+1} &= A_t + C_t \\ \nonumber C_{t+1} &= B_t \\ \nonumber B_{t+1} &= k A_t \end{align} \end{split}\]

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

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:

\[ 20000 + \underbrace{0.05 \cdot 20000}_\text{interest} - \underbrace{2000}_\text{payment} = 19000 \]

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:

\[ 1000 + 0.05 \cdot 1000 = 1050 \]

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#

image

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

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:

\[\begin{split} \begin{align} \nonumber S_{t+1} &= S_t - \beta S_t I_t \\ \nonumber I_{t+1} &= I_t + \beta S_t I_t - \gamma I_t \\ \nonumber R_{t+1} &= R_t + \gamma I_t \end{align} \end{split}\]

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

\[ T_n = \frac{n(n+1)(n+2)}{6} \]

and a sequence of tetrahedral numbers is

\[ 1,\, 4,\, 10,\, 20,\, 35,\, 56,\, 84,\, 120,\, 165,\, 220, \ldots \]

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