Exercises Laboratorio di Calcolo: The Python Language¶

By Hendrik Speleers, AY 2024-2025

Import all modules used in the exercises¶

In [1]:
import math
import random

Exercise 1¶

Write a function that computes the factorial of a given integer number.

In [2]:
def factorial(n):
    fac = 1
    for i in range(2, n+1):
        fac *= i
    return fac
In [3]:
factorial(10)
Out[3]:
3628800
In [4]:
math.factorial(10)  # check
Out[4]:
3628800

Exercise 2¶

Write a function that displays the $n$ first terms of the Fibonacci sequence, defined by: $$F_0 = 1$$ $$F_1 = 1$$ $$F_{n} = F_{n-1} + F_{n-2}$$

In [5]:
def fibonacci(n):
    f0, f1 = 1, 1
    for i in range(n):
        print(f0)
        f0, f1 = f1, f0 + f1
In [6]:
fibonacci(10)
1
1
2
3
5
8
13
21
34
55

Exercise 3¶

Write a program to generate all sentences where the subject is in ['I', 'You'] and the verb is in ['Play', 'Love'] and the object is in ['Football', 'Tennis'].

In [7]:
subjects = ['I', 'You']
verbs = ['Play', 'Love']
objects = ['Football', 'Tennis']
for s in subjects:
    for v in verbs:
        for o in objects:
            sentence = '%s %s %s.' % (s, v, o)
            print(sentence)
I Play Football.
I Play Tennis.
I Love Football.
I Love Tennis.
You Play Football.
You Play Tennis.
You Love Football.
You Love Tennis.

Exercise 4¶

  1. Write a function that returns all items on even positions of a list.
  2. Write a function that returns all items of a list, except the first and last one, in reversed order.
In [8]:
def list_even(vals):
    return vals[::2]
In [9]:
def list_rev_last(vals):
    return vals[-2:0:-1]
In [10]:
vals = [2, 5, 7, 9, 11, 17, 222]
print(list_even(vals))
print(list_rev_last(vals))
[2, 7, 11, 222]
[17, 11, 9, 7, 5]

Exercise 5¶

Write a function that calculates the values of $Q$ according to the formula: $$Q=\sqrt{\frac{2CD}{H}}$$ The values of $C$ and $H$ are fixed: $C = 50$ and $H = 30$. The values of $D$ should be input to your function as a list. Return all corresponding values of $Q$ in a list.

In [11]:
def compute_Q(D):
    C = 50
    H = 30
    Q = [math.sqrt(2.0*C*d/H) for d in D]
    return Q
In [12]:
compute_Q([1, 2, 3])
Out[12]:
[1.8257418583505538, 2.581988897471611, 3.1622776601683795]

Exercise 6¶

Write a program that finds all integer numbers which are divisible by 7 but are not a multiple of 5, between 200 and 300 (both included). Return these numbers in a list.

In [13]:
l = [i for i in range(200, 301) if i%7 == 0 and i%5 != 0]
In [14]:
l
Out[14]:
[203, 217, 224, 231, 238, 252, 259, 266, 273, 287, 294]

Exercise 7¶

Write a function that finds the positions of all the numbers other than zero in a given list. Return these positions in a list.

In [15]:
def find_nonzero(vals):
    nz = [idx for idx, val in enumerate(vals) if val != 0] 
    return nz
In [16]:
find_nonzero([6, 7, 0, 1, 0, 2, 0, 12])
Out[16]:
[0, 1, 3, 5, 7]

Exercise 8¶

Write a function that generates a matrix of size $(n, m)$ for given integer numbers $n, m$. The element value in the $i$-th row and $j$-th column of the matrix should be $i \cdot j$.

In [17]:
def special_matrix(n, m):
    M = [[i*j for j in range(m)] for i in range(n)]
    return M
In [18]:
special_matrix(3, 5)
Out[18]:
[[0, 0, 0, 0, 0], [0, 1, 2, 3, 4], [0, 2, 4, 6, 8]]

Exercise 9¶

Write a function that accepts a list of words as input, and returns the words after removing all duplicate words and sorting them alphanumerically.

In [19]:
def manipulate_words(words):
    return sorted(set(words))
In [20]:
def manipulate_sentence(text):
    words = text.split()
    nwords = manipulate_words(words)
    return ' '.join(nwords)
In [21]:
text = 'hello world and practice makes perfect and hello world again'
manipulate_sentence(text)
Out[21]:
'again and hello makes perfect practice world'

Exercise 10¶

A robot moves in a plane starting from the original point (0,0). The robot can move in the directions UP, DOWN, LEFT and RIGHT with a given number of steps. Write a function to calculate the distance from the original point to the current position after a list of movements. Movements are indicated as a tuple ('DIRECTION', steps).

In [22]:
def distance(moves):
    pos = [0, 0]
    for move in moves:
        dirs = move[0]
        steps = move[1]
        if dirs == 'UP':
            pos[0] += steps
        elif dirs == 'DOWN':
            pos[0] -= steps
        elif dirs == 'LEFT':
            pos[1] -= steps
        elif dirs == 'RIGHT':
            pos[1] += steps
        else:
            pass
    dist = math.sqrt(pos[0]**2 + pos[1]**2)
    return dist
In [23]:
moves = [('UP', 5), ('DOWN', 3), ('LEFT' , 3), ('RIGHT', 2)]
distance(moves)
Out[23]:
2.23606797749979

Exercise 11¶

Write a binary search function which checks whether an item is in a sorted list or not. The function should return True if the item is in the list.

In [24]:
def naive_search(vals, val):
    for v in vals:
        if val == v: return True
    return False
In [25]:
def bin_search(vals, val):
    start = 0
    stop = len(vals)-1
    while start < stop:
        mid = (start + stop) // 2
        if val <= vals[mid]:
            stop = mid
        else:
            start = mid + 1
    return val == vals[start]
In [26]:
vals = [2, 5, 7, 9, 11, 17, 222]
print(bin_search(vals, 11))
print(bin_search(vals, 12))
True
False
In [27]:
vals = [random.randint(1, 1000) for i in range(1000000)]
val = 951
%timeit naive_search(vals, val)
%timeit bin_search(vals, val)
19.1 µs ± 152 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)
1.12 µs ± 13.6 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)

Exercise 12¶

Project Euler is a website with mathematical problems that should/could be solved by computers. Go to the website http://projecteuler.net and solve some of the problems using Python.

Euler problem 6: sum square difference¶

The sum of the squares of the first ten natural numbers is $$1^2 + 2^2 + \ldots + 10^2 = 385.$$ The square of the sum of the first ten natural numbers is $$(1 + 2 + \ldots + 10)^2 = 55^2 = 3025.$$ Hence the difference between the sum of the squares of the first ten natural numbers and the square of the sum is $$3025 − 385 = 2640.$$ Find the difference between the sum of the squares of the first one hundred natural numbers and the square of the sum.

In [28]:
N = 100
sum_square = sum(n**2 for n in range(1, N+1))
square_sum = sum(range(1, N+1))**2
diff_sums = square_sum - sum_square
In [29]:
diff_sums
Out[29]:
25164150

Euler problem 16: power digit sum¶

$2^{15} = 32768$ and the sum of its digits is $3 + 2 + 7 + 6 + 8 = 26$. What is the sum of the digits of the number $2^{1000}$ ?

In [30]:
N = 1000
digits = str(2**N)
sum_digits = sum(int(digit) for digit in digits)
In [31]:
sum_digits
Out[31]:
1366
In [ ]: