By Hendrik Speleers, AY 2024-2025
import math
import random
Write a function that computes the factorial of a given integer number.
def factorial(n):
fac = 1
for i in range(2, n+1):
fac *= i
return fac
factorial(10)
3628800
math.factorial(10) # check
3628800
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}$$
def fibonacci(n):
f0, f1 = 1, 1
for i in range(n):
print(f0)
f0, f1 = f1, f0 + f1
fibonacci(10)
1 1 2 3 5 8 13 21 34 55
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'].
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.
def list_even(vals):
return vals[::2]
def list_rev_last(vals):
return vals[-2:0:-1]
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]
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.
def compute_Q(D):
C = 50
H = 30
Q = [math.sqrt(2.0*C*d/H) for d in D]
return Q
compute_Q([1, 2, 3])
[1.8257418583505538, 2.581988897471611, 3.1622776601683795]
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.
l = [i for i in range(200, 301) if i%7 == 0 and i%5 != 0]
l
[203, 217, 224, 231, 238, 252, 259, 266, 273, 287, 294]
Write a function that finds the positions of all the numbers other than zero in a given list. Return these positions in a list.
def find_nonzero(vals):
nz = [idx for idx, val in enumerate(vals) if val != 0]
return nz
find_nonzero([6, 7, 0, 1, 0, 2, 0, 12])
[0, 1, 3, 5, 7]
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$.
def special_matrix(n, m):
M = [[i*j for j in range(m)] for i in range(n)]
return M
special_matrix(3, 5)
[[0, 0, 0, 0, 0], [0, 1, 2, 3, 4], [0, 2, 4, 6, 8]]
Write a function that accepts a list of words as input, and returns the words after removing all duplicate words and sorting them alphanumerically.
def manipulate_words(words):
return sorted(set(words))
def manipulate_sentence(text):
words = text.split()
nwords = manipulate_words(words)
return ' '.join(nwords)
text = 'hello world and practice makes perfect and hello world again'
manipulate_sentence(text)
'again and hello makes perfect practice world'
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).
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
moves = [('UP', 5), ('DOWN', 3), ('LEFT' , 3), ('RIGHT', 2)]
distance(moves)
2.23606797749979
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.
def naive_search(vals, val):
for v in vals:
if val == v: return True
return False
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]
vals = [2, 5, 7, 9, 11, 17, 222]
print(bin_search(vals, 11))
print(bin_search(vals, 12))
True False
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)
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.
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.
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
diff_sums
25164150
$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}$ ?
N = 1000
digits = str(2**N)
sum_digits = sum(int(digit) for digit in digits)
sum_digits
1366