Skip to content

Exercises

Instructions

  • Do not seek help from AI or genAI

Series 1

  1. Write a Python script that asks the user to enter an integer and displays whether the number is even or odd. đź’ˇ Tip: use n = int(input("Enter an integer: "))
  2. Write a Python script that asks the user to enter an integer n and displays the sum of the first n integers (sum of integers from 0 to n inclusive).
  3. Write a Python script that asks the user to enter an integer and displays all the divisors of that number.
  4. Write a Python script that generates two random numbers x and y with 0 <= x <= 10 and x <= y <= 100. (tip: import random and call x = random.randint(0, 10)).
  5. Write a Python program that generates two random numbers x and y with 0 <= x <= 10 and x <= y <= 100. The program then displays the result of the integer division between y and x and the remainder of the division. (remember to handle the case where x = 0).
  6. Write a program that displays as many characters as possible from a string in a pyramid sequence. (tip: you can use a for loop on a string for char in string).

    • Example for the string "abcdefghijklmnopqrstuvwxyz" * 10
    a 
    bc 
    def 
    ghij 
    klmno 
    pqrstu 
    vwxyzab 
    cdefghij 
    klmnopqrs 
    tuvwxyzabc 
    defghijklmn 
    opqrstuvwxyz 
    abcdefghijklm 
    nopqrstuvwxyza 
    bcdefghijklmnop 
    qrstuvwxyzabcdef 
    ghijklmnopqrstuvw 
    xyzabcdefghijklmno 
    pqrstuvwxyzabcdefgh 
    ijklmnopqrstuvwxyzab 
    cdefghijklmnopqrstuvw 
    xyzabcdefghijklmnopqrs
    
  7. Write a function count_letters(text) that takes a string argument text and returns a dictionary containing the frequency of all letters in the input string. For example: count_letters("hello") returns {"h": 1, "e": 1, "l": 2, "o": 1}.

  8. Given rectangles defined with dictionaries where the keys are "x", "y", "width", "height", where x and y are the coordinates of the rectangle (we suppose that the origin (0, 0) is the top left corner of the screen) and width and height are its dimensions in pixel units
    • Write a function is_intersecting(rectangle1, rectangle2) that returns True if there is an intersection between the two rectangles.
    • Write a function get_intersection(rectangle1, rectangle2) that returns the intersecting rectangle if it exists, otherwise None.
  9. Write a function fx_square(x) that returns the result of x * x.
    • Write a function fx_square_list(n) that returns a list of n elements. The value of an element at index i is fx_square(i).
    • Use the matplotlib library to draw a graph where the x-axis represents integers from 0 to n and the y-axis represents the elements returned by fx_square_list(n).
  10. Define a function fx_square_list2(points) that takes a list of integers sorted in ascending order and returns a new list where the value of the i-th element is points[i] * points[i].
    • Plot the graph of f(x) = x * x for x ranging from -100 to 100.
  11. Plot the graph from -100 to 100 for the following functions: exp(x), 1/x, log(x) + (1/(x^3))

Solutions Series 1

Exercises 1 to 5
n = int(input("Saisir un entier : "))

print(n, "est", "pair" if n % 2 == 0 else "impair")
print(("pair", "impair")[n % 2])

somme_n = 0
for i in range(n + 1):
    somme_n += i

print("Somme des", n, "premiers entiers", somme_n)

for i in range(1, n):
    if n % i == 0:
        print(i, "est un diviseur de", n)
Exercises pyramid, count_letters, and intersection
print([1, 2, 3] * 3)
print("hello" * 2)
print(len([1, 2, 3]), len([1, 2, 3] * 3), len("hello"))


# abcdefghij
# ligne 0 -> a on prend la sous-chaine (0, 1)
# ligne 1 -> bc (1, 3)
# ligne 2 -> def (3, 6)
# ligne 3 -> ghij (6, 10)
# ligne l -> (indice courant dans la chaine, indice courant + l + 1)
# indice courant s'incrémente à chaque fois de l + 1


def print_pyramide(input):
    i = 0
    current_line = 0
    while i + current_line + 1 < len(input):
        print(input[i : i + current_line + 1])
        i += current_line + 1
        current_line += 1


print_pyramide("abcdefghij")
print_pyramide("abcdefghijklmnopqrstuvwxyz")
print_pyramide("abcdefghijklmnopqrstuvwxyz" * 10)


def count_letters1(input):
    dict = {}
    for letter in input:
        if letter in dict:
            dict[letter] += 1
        else:
            dict[letter] = 1
    return dict


def count_letters2(input):
    dict = {}
    for letter in input:
        dict[letter] = dict.get(letter, 0) + 1
    return dict


def count_letters3(input):
    dict = {}
    for letter in input:
        dict[letter] = dict[letter] + 1 if letter in dict else 1
    return dict


print(count_letters1("hello"))
print(count_letters2("hello"))
print(count_letters3("hello"))


def is_intersect_1D(x1, l1, x2, l2):
    # Dans d'autres langages, il aurait fallu écrire (On ne peut pas combiner les inégalités)
    # x1 < x2 && x2 < x1 + l1 || x2 < x1 && x1 < x2 + l2
    return x1 <= x2 <= x1 + l1 or x2 <= x1 <= x2 + l2


print(is_intersect_1D(0, 10, 3, 1))
print(is_intersect_1D(2, 5, 10, 4))
print(is_intersect_1D(-2, 5, 10, 4))
print(is_intersect_1D(0, 10, -10, 20))
print(is_intersect_1D(100, 1, -5, 1000))
print(is_intersect_1D(100, 1, -5, 106))
print(is_intersect_1D(100, 1, -5, 99))


def is_intersect_2D(rec1, rec2):
    return is_intersect_1D(
        rec1["x"], rec1["width"], rec2["x"], rec2["width"]
    ) and is_intersect_1D(rec1["y"], rec1["height"], rec2["y"], rec2["height"])


rec1 = {"x": 10, "y": 30, "width": 100, "height": 200}
rec2 = {"x": -5, "y": 20, "width": 50, "height": 100}
rec3 = {"x": 15, "y": 15, "width": 5, "height": 5}
rec4 = {"x": 15, "y": 15, "width": 5, "height": 400}
print("testing intersect 2D")
print("rec1, rec2", is_intersect_2D(rec1, rec2))
print("rec1, rec3", is_intersect_2D(rec1, rec3))
print("rec1, rec4", is_intersect_2D(rec1, rec4))
print("rec2, rec3", is_intersect_2D(rec2, rec3))
plot
import matplotlib.pyplot as plt


def fx_square(x):
    return x**2


def fx_square_list(n):
    items = []
    for i in range(n):
        items.append(fx_square(i))
    return items


def plot_f(n):
    plt.plot(range(n), fx_square_list(n))
    plt.show()


n = 88
print(fx_square_list(n))
plot_f(n)


# exemple de liste points: [-3, 0, 1, 4, 5]
# Exemple de sortie attendue [9, 0, 1, 16, 25]


def fx_square_list2(points):
    values = []
    for point in points:
        values.append(point**2)
    return values


points = range(-100, 100)
values = fx_square_list2(points)
plt.plot(points, values)
plt.show()

Series 2

Solve the following exercises using comprehensions.

  1. Create a list of the first 10 even numbers.
  2. Create a dictionary containing 10 keys ranging from 0 to 9. The value of each key is a text indicating the parity of the number. (example: {0: "even", 1: "odd", etc.})
  3. Create a dictionary containing 10 keys ranging from 0 to 9 converted to strings. The value of each key is a text indicating the parity of the number. (example: {"0": "even", "1": "odd", etc.})
  4. Create a dictionary that filters the previous dictionary, keeping only the odd numbers.
  5. Create a tuple that contains the first 20 even numbers.
  6. Given a list of students where each student is defined by a dictionary of this type student = {"name": "sasha", "birth_year" = 2000}:
    • Create a set of student names.
    • Create a tuple containing the birth years of each student.
  7. From a tuple of symbols ("♥️", "♠️", "♣️", "♦️") and a list of ranks ["Ace", "King", "Queen", "Jack"] + [*range(2, 11)], create a deck of cards as a list of tuples which is the Cartesian product of the symbols and the ranks.
Solutions
# 1
print([x for x in range(0, 20, 2)])
print([x for x in range(0, 20) if x % 2 == 0])

# 2
print({x: "even" if x % 2 == 0 else "odd" for x in range(10)})


def get_parity(x):
    if x % 2 == 0:
        return "even"
    else:
        return "odd"


print({x: get_parity(x) for x in range(10)})

# 3
print({str(x): "even" if x % 2 == 0 else "odd" for x in range(10)})
print({f"{x}": "even" if x % 2 == 0 else "odd" for x in range(10)})

# 4
numbers = {f"{x}": "even" if x % 2 == 0 else "odd" for x in range(10)}
print({key: value for key, value in numbers.items() if int(key) % 2 != 0})

# 5
print((x for x in range(0, 40, 2)))

# cartes
symbols = ("♥️", "♠️", "♣️", "♦️")
ranks = ["As", "Roi", "Reine", "Valet"] + [*range(2, 11)]

cards = [(symbol, rank) for symbol in symbols for rank in ranks]
print(cards)

# 6
students = [
    {"name": "Olive", "birth_year": 2001},
    {"name": "Tom", "birth_year": 1975},
    {"name": "Alf", "birth_year": 1701},
]
print({x["name"] for x in students})
print(tuple(x["birth_year"] for x in students))

Source