22. Exercices d’entrainement#
La liste des exercices ci-dessus sont dédiés à l’entrainement. Ils sont indépendant les uns des autres. Ils concernent des notions précises du cours et vous propose des solitions. Il est conseillé de ne pas regarder les solutions sauf pour vérifer sa solution ou si vous êtes vraiment bloqué.
22.1. If Statement#
22.1.1. Positive, Negative, or Zero#
Write a Python function that takes an integer as input and prints if the number is positive, negative, or zero.
def test(number):
pass
#number = int(input("Enter a number: "))
#test(number)
Solution - Click the button to reveal!
def test(number):
if number > 0:
print(f"{number} is positive.")
elif number < 0:
print(f"{number} is negative.")
else:
print(f"{number} is zero.")
number = int(input("Enter a number: "))
test(number)
22.1.2. Even or Odd#
Write a Python program that takes an integer as input and checks if the number is even or odd.
def even_odd(x):
pass
#number = int(input("Enter a number: "))
#even_odd(number)
Solution - Click the button to reveal!
def even_odd(number):
if number % 2 == 0:
print(f"{number} is even.")
else:
print(f"{number} is odd.")
number = int(input("Enter a number: "))
even_odd(number)
22.1.3. Leap Year Check#
Write a Python program that checks if a given year is a leap year or not. A year is a leap year if:
It is divisible by 4.
But, it is not a leap year if it is divisible by 100 unless it is also divisible by 400.
def leap_year(year):
pass
#number = int(input("Enter a year: "))
#print(leap_year(number))
Solution - Click the button to reveal!
def leap_year(year):
if year % 4 == 0:
if year % 100 == 0:
if year % 400 == 0:
return True
else:
return False
else:
return True
else:
return False
def leap_year_v2(year):
if (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0):
return True
else:
return False
22.1.4. Grading System#
Write a Python program that takes a student’s score as input (out of 100) and prints the corresponding grade based on the following conditions:
90 to 100: Grade A
80 to 89: Grade B
70 to 79: Grade C
60 to 69: Grade D
Below 60: Grade F
def grading(score):
pass
#score = int(input("Enter a score: "))
#print(grading(score))
Solution - Click the button to reveal!
def grading(score):
if score < 60:
return "E"
elif score < 70:
return "D"
elif score < 80:
return "C"
elif score < 90:
return "B"
elif score <= 100:
return "A"
else:
return None
22.2. While statement#
22.2.1. Sum of First N Natural Numbers#
Write a Python function that takes an integer n
as input and uses a while loop to calculate the sum of the first n
natural numbers \((1, 2, 3, ..., n)\).
def sum_int(n):
pass
#s = sum_int(5)
#print(s)
Solution - Click the button to reveal!
def sum_int(n):
i = 1
s = 0
while i <= n:
s+=i
i+=1
return s
22.2.2. Multiplication Table#
Write a Python function that takes an integer as input and prints the multiplication table for that number using a while loop. Example of output:
7 x 1 = 7
7 x 2 = 14
7 x 3 = 21
...
7 x 10 = 70
def multplication_table(x):
pass
#multplication_table(12)
Solution - Click the button to reveal!
def multplication_table(x):
i = 1
while i <= 10:
print(f"{x} x {i} = {x * i}")
i += 1
22.3. Tuple#
22.3.1. Searching a value#
Write a function that takes a tuple as input and a value v
and return True
if v
is a value in the tuple or False
otherwise.
Note: Obvisouly, it’s better to use the in
operator which is doing the same. But we want to pratice the while
loop.
def is_in(t, v):
pass
#t = ("a", "b", "c", 2, 4)
#print(is_in(t, 3)) # False
#print(is_in(t, 4)) # True
Solution - Click the button to reveal!
def is_in(t, v):
i = 0
while i < len(t):
if t[i] == v:
return True
i+=1
return False
22.3.2. Searching min value#
Write a function that takes a tuple as input and return the minimum value of a tuple.
Note: Obvisouly, it’s better to use the min
and max
functions for such operations but we want to pratice the while
loop.
def min_value(t):
pass
#t = (1, 2, 8, 0, 10, 10, 3)
#print(min_value(t))
Solution - Click the button to reveal!
def min_value(t):
i = 0
imin = 0
while i < len(t):
if t[i] < t[imin]:
imin = i
i+=1
return t[imin]
22.3.3. Searching extreme values#
Write a function that takes a tuple as input and return the minimum and the maximum values of a tuple. Remember that a function may return a tuple.
def extreme_values(t):
pass
#t = (1, 2, 8, 0, 10, 10, 3)
#print(extreme_values(t))
Solution - Click the button to reveal!
def extreme_values(t):
i = 0
imin = 0
imax = 0
while i < len(t):
if t[i] < t[imin]:
imin = i
if t[i] > t[imax]:
imax = i
i+=1
return t[imin], t[imax]
22.4. List and For Loop#
22.4.1. List of Squares#
Write a function squares
that takes a list of numbers and returns a new list where each element is the square of the corresponding element in the input list.
def squares(lst):
pass
#print(squares([1, 2, 3, 5, 12])) # [1, 4, 9, 25, 144]
Solution - Click the button to reveal!
def squares(lst):
nl = []
for x in lst:
nl.append(x*x)
return nl
Solution (using list comprehension) - Click the button to reveal!
def squares(lst):
return [x**2 for x in lst]
22.4.2. Count Occurrences of an Element#
Write a function count_occurrences
that takes a list and an element, and returns the number of times that element appears in the list.
def count_occurrences(lst, elt):
c = 0
for e in lst:
if e == elt:
c+=1
return c
#count_occurrences([1, 2, 2, 3, 2, 4, 5], 2) # output 3
Solution - Click the button to reveal!
def count_occurrences(lst, elt):
c = 0
for e in lst:
if e == elt:
c+=1
return c
22.4.3. List Intersection#
Write a function list_intersection
that takes two lists and returns a new list containing only the elements that appear in both lists (the intersection).
def list_intersection(lst1, lst2):
pass
#print(list_intersection([1, 2, 3, 4], [3, 4, 5, 6])) # Output: [3, 4]
Solution - Click the button to reveal!
def list_intersection(lst1, lst2):
l = []
for e in lst1:
if e in lst2:
l.append(e)
return l
Solution (using list comprehension) - Click the button to reveal!
def list_intersection(lst1, lst2):
return [item for item in lst1 if item in lst2]
22.4.4. Remove Duplicates from a List#
Write a function remove_duplicates
that takes a list and returns a new list with all duplicates removed. The order of the elements should be preserved.
def remove_duplicates(lst):
unique_list = []
for item in lst:
if item not in unique_list:
unique_list.append(item)
return unique_list
# Example usage
#l1 = [1, 2, 2, 3, 4, 4, 5]
#l2 = remove_duplicates(l1)
#print(l2) # Output: [1, 2, 3, 4, 5]
#print(id(l1), id(l2)) # Should be different
Solution - Click the button to reveal!
def remove_duplicates(lst):
unique_list = []
for item in lst:
if item not in unique_list:
unique_list.append(item)
return unique_list
22.5. Slices#
22.5.1. Manipulate Slice#
Using slices, make the following operations
Extract the 5 first characters
Extract the 5 last characters
Extract from the second characters to the third.
Extract 1 over 2 characters
Invert the string
s = "abcdefghijklmnopqrstuvwxyz"
# s[ ???? ]
Solution (using list comprehension) - Click the button to reveal!
print(s[:5])
print(s[-5:])
print(s[1:3])
print(s[::2])
print(s[::-1])
22.5.2. Palindrome#
Write a function palindrome
that takes a string as input and return True if the string is a palindrome.
Note: A palindrome is a word, number, phrase, or other sequence of symbols that reads the same backwards as forwards, such as madam or racecar.
def check_palindrome(s):
pass
#check_palindrome("racecar")
Solution (using list comprehension) - Click the button to reveal!
def check_palindrome(s):
return s == s[::-1]