Note: Ceci est une traduction française du quiz d’évaluation des compétences Python de LinkedIn. Pour la version originale en anglais, consultez python-quiz.md.
any() sur une liste ?any() retourne aléatoirement n’importe quel élément de la liste.any() renvoie True si n’importe quel élément de la liste s’évalue à True. Sinon, elle renvoie False.any() prend comme arguments la liste à vérifier et l’élément à rechercher. Si “n’importe lequel” des éléments de la liste correspond à l’élément recherché, la fonction renvoie True.any() renvoie une valeur booléenne qui répond à la question “Y a-t-il des éléments dans cette liste ?”exemple
if any([True, False, False, False]) == True:
print('Yes, there is True')
>>> 'Yes, there is True'
ensemble
None.def get_next_card():
# corps de la méthode ici
def get_next_card(self):
# corps de la méthode ici
def self.get_next_card():
# corps de la méthode ici
def self.get_next_card(self):
# corps de la méthode ici
my_list = (2, 'apple', 3.5)my_list = [2, 'apple', 3.5]my_list = [2, 'apple', 3.5].to_list()my_list = to_list(2, 'apple', 3.5)get_max_num([57, 99, 31, 18])call.(get_max_num)def get_max_num([57, 99, 31, 18])call.get_max_num([57, 99, 31, 18])my_game = Game(self) self.my_game.roll_dice()my_game = Game() self.my_game.roll_dice()my_game = Game() my_game.roll_dice()my_game = Game(self) my_game.roll_dice(self)num_list = [21, 13, 19, 3, 11, 5, 18]
num_list.sort()
num_list[len(num_list) // 2]
Explication : // est l’opérateur de division entière, qui est une opération de division normale qui retourne le plus grand entier possible, inférieur ou égal au résultat de la division normale. Ici, il est utilisé pour trouver la médiane, qui est la valeur séparant la moitié supérieure de la moitié inférieure d’un échantillon de données, en trouvant l’index de l’élément de la liste au milieu de la liste. (Ceci est suffisant pour une liste avec un nombre impair d’éléments ; si la liste avait un nombre pair d’éléments, vous feriez la moyenne des valeurs des deux éléments du milieu pour trouver la valeur médiane.)
vector de type np.array avec 10 000 éléments. Comment pouvez-vous transformer vector en une variable nommée matrix avec des dimensions 100x100 ?matrix = (vector.shape = (100,100))matrix = vector.to_matrix(100,100)matrix = matrix(vector,100,100)matrix = vector.reshape(100, 100)def myFunction(country = "France"):
print(f"Hello, I am from {country}")
myFunction("Spain")
myFunction("")
myFunction()
Hello, I am from Spain
Hello, I am from
Hello, I am from
Hello, I am from France
Hello, I am from France
Hello, I am from France
Hello, I am from Spain
Hello, I am from
Hello, I am from France
Hello, I am from Spain
Hello, I am from France
Hello, I am from France

sum(titanic['Survived'])[x for x in titanic['Survived'] if x == 1]len(titanic["Survived"])sum(titanic['Survived']==0)Explication : Le titanic['Survived'] retourne un objet pandas.Series, qui contient la colonne Survived du DataFrame.
L’addition des valeurs de cette colonne (c’est-à-dire sum(titanic['Survived'])) retourne le nombre total de survivants car un survivant est représenté par un 1 et une perte par 0.
characters = ["Iron Man", "Spider Man", "Captain America"]
actors = ["Downey", "Holland", "Evans"]
# sortie exemple : [("IronMan", "Downey"), ("Spider Man", "Holland"), ("Captain America", "Evans")]
[(x,y)] for x in characters for y in actors]zip(characters, actors)
d = {}
for x in range(1, len(characters)):
d[x] = actors[x]
{x:y for x in characters for y in actors}{x : x*x for x in range(1,100)}
x comme clé, et x au carré comme valeur ; de 1 à 100.x comme clé, et x au carré comme valeur ; de 1 à 99.x, x au carré) ; de 1 à 99.
def jaccard(a, b): return len (a | b) / len (a & b)def jaccard(a, b): return len (a & b) / len (a | b)def jaccard(a, b): return len (a && b) / len (a || b)def jaccard(a, b): return a.intersection(b) / a.union(b)[1,2,3] * 3
[3,2,3][1, 2, 3, 1, 2, 3, 1, 2, 3][3,6,9][1,2,3,4], quelle est la valeur de numbers[-2] ?__init__() qui ne prend aucun paramètre ?def __init__(self): passclass __init__(self): passclass __init__(): passdef __init__(): pass
using math.sinimport math.sinfrom math import sinimport sin from mathExplication : L’instruction from..import vous permet d’importer des fonctions/variables spécifiques d’un module au lieu de tout importer.
0le nombre de toutes les valeurs Trueune erreur de typeNoneprint("foo" if (256).bit_length() > 8 else "bar")
TruefoobarTrue.RuntimeError si vous ne retournez pas de valeur.None.Explication : La bibliothèque Pandas est couramment utilisée pour travailler avec des données tabulaires, telles que des données sous forme de tableaux ou de feuilles de calcul. Elle fournit des structures de données et des fonctions pour la manipulation et l’analyse de données. D’autre part, NumPy est une bibliothèque puissante pour le calcul numérique en Python, et elle est souvent utilisée pour effectuer des opérations mathématiques sur des données numériques, telles que des tableaux et des matrices.
gcc ou clang.pip ou conda.
random.uniform(0,50);plt.histrandom.gauss(50,20);plt.histrandom();plt.scatterrandom.triangular(0,50);plt.bara et b ?import numpy as np
a = np.arange(100)
b = a[50:60:2]
a : tous les entiers de 0 à 99 (inclus) ; b : tous les entiers pairs de 50 à 58 (inclus).a : tous les entiers de 0 à 100 (inclus) ; b : tous les entiers pairs de 50 à 60 (inclus).a : tous les entiers de 0 à 99 (inclus) ; b : tous les entiers pairs de 50 à 60 (inclus).a : tous les entiers de 0 à 99 (inclus) ; b : tous les entiers impairs de 49 à 59 (inclus).my_object ?my_object.get_shape()my_object.shapemy_object.dim()len(my_object)mylist et que vous souhaitiez rechercher une valeur spécifique. Le nombre minimum de comparaisons sera _ et le nombre maximum de comparaisons sera _ ?len(mylist); len(mylist)1; len(mylist)2; len(mylist)0; len(mylist)Explication : On peut utiliser une instruction break et la valeur recherchée peut être le premier élément de la liste, étant donné qu’elle est non vide.
0TrueNoneFalseimport numpy as np
def can_matrices_be_multiplied (matrix1, matrix2):
rowsMat1, columnsMat1 = matrix1.shape
rowsMat2, columnsMat2 = matrix2.shape
if _____ == ______ :
print("Les matrices peuvent être multipliées !")
return True
else:
return False
référence. Une matrice peut être multipliée par toute autre matrice qui a le même nombre de lignes que la première a de colonnes. Par exemple, une matrice avec 2 colonnes peut être multipliée par toute matrice avec 2 lignes
[(x, x+1) for x in range(1,5)]
class Father():
name = 'Robert'
class Person(Father):
def __init__(self, name):
self.fathername = super.name
self.name = name
def introduce(self):
print(f"My name is {self.name} son of {self.fathername}")
king = Person("Joffrey")
king.introduce()
class Father():
name = 'Robert'
class Person(Father):
def __init__(self, name):
self.fathername = self.name
self.name = name
def introduce(self):
print(f"My name is {self.name} son of {self.fathername}")
king = Person("Joffrey")
king.introduce()
class Father():
name = 'Robert'
class Person(Father):
def __init__(self, name):
self.name = name
def introduce(self):
print(f"My name is {self.name} son of {super.name}")
king = Person("Joffrey")
king.introduce()
class Father():
name = 'Robert'
class Person(Father):
def __init__(self, name):
self.name = name
def introduce(self):
print(f"My name is {self.name} son of {base.name}")
king = Person("Joffrey")
king.introduce()
Explication : Dans le premier, super n’a pas .name (devrait être self.name). Le troisième perd Robert, et base n’est pas défini dans le 4ème.
animals = {
'a': ['ant', 'antelope', 'armadillo'],
'b': ['beetle', 'bear', 'bat'],
'c': ['cat', 'cougar', 'camel']
}
animals = defaultdict(list, animals)
print(animals['b'])
print(animals['d'])
['beetle', 'bear', 'bat']
[]
['beetle', 'bear', 'bat']
# an exception will be thrown
['beetle', 'bear', 'bat']
None
['bat', 'bear', 'beetle']
[]
Explication : Les dictionnaires entraînent généralement une exception lors de l’utilisation de la syntaxe des crochets. Defaultdict ici retourne une valeur par défaut dédiée par le premier paramètre, donc au lieu de lever une exception, ils retournent la valeur par défaut. Notez que cela doit être importé comme suit : from collections import defaultdict
n est déjà défini comme toute valeur entière positive.)[x*2 for x in range(1,n)]
x = 18
if x > 10:
if x > 15:
print('A')
else:
print('B')
else:
print('C')
CBABCréférence Aucune longueur fixe n’est spécifiée mais Pep-8 spécifie sous “Longueur maximale de ligne” de “Limiter toutes les lignes à un maximum de 79 caractères”.
i lorsque la boucle suivante terminera son exécution ?for i in range(5): pass
f-strings sont également appelées :Explication : Le threading Python est limité à un seul CPU à la fois. La bibliothèque multiprocessing vous permettra d’exécuter du code sur différents processeurs.
y dans ce code ?x = 5
y = 1 + (20 if x < 5 else 30)
False21231Explication : Si vous n’avez qu’une seule instruction à exécuter, une pour if et une pour else, vous pouvez tout mettre sur la même ligne.
x = 5
# This is the same statement expanded to multiple lines
y = 1
if (x < 5):
y += 20
else:
y += 30
référence
“Pickling” est le processus par lequel une hiérarchie d’objets Python est convertie en flux d’octets, et “unpickling” est l’opération inverse, par laquelle un flux d’octets (provenant d’un fichier binaire ou d’un objet de type bytes) est reconverti en hiérarchie d’objets.
print("codescracker".endswith("er"))
True12Falseprint("programming".center())
crprogrammingTypeError: center expected at least 1 argument, got 0.reference. The center() method will center align the string, using a specified character (space is the default) as the fill character.
Syntax: string.center(length, character) where length is required!
x = 1j
print(x**2 == -1)
j has not been initialized.True1jFalseExplanation: The letter j acts as the imaginary unit in Python, therefore x**2 means j**2 which is equal to -1. The statement x**2 == -1 is evaluated as True.
print(0xA + 0xB + 0xC)
33630xA + 0xB + 0xCNoneExplanation: A, B and C are hexadecimal integers with values 10, 11 and 12 respectively, so the sum of A, B and C is 33.
for i in range(5):
print(i)
else:
print("Done!")
1
2
3
4
5
Done!
0
1
2
3
4
5
Done!
0
1
2
3
4
Done!
execution_fn function:import functools
import time
def timer(MISSING_ARG_1):
@functools.wraps(func)
def wrapper(*args, **kwargs):
start_time = time.perf_counter()
rval = func(*args, **kwargs)
end_time = time.perf_counter()
duration = end_time - start_time
print(f"Executed in {duration:.4f} seconds")
return MISSING_ARG_2
return MISSING_ARG_3
@timer
def execution_fn():
for i in range(3):
time.sleep(1)
execution_fn()
Which of the following choices are the missing arguments?
MISSING_ARG_1 = wrapper
MISSING_ARG_2 = rval
MISSING_ARG_3 = func
MISSING_ARG_1 = func
MISSING_ARG_2 = rval
MISSING_ARG_3 = wrapper
MISSING_ARG_1 is empty
MISSING_ARG_2 = rval
MISSING_ARG_3 = wrapper
MISSING_ARG_1 is empty
MISSING_ARG_2 = rval
MISSING_ARG_3 = func
Dog in Python?class Dog:Dog class:Dog:class Dogscikit-learn, import from the scikit-learn._ submodule.preprocessingpipelinefilterspipe_filterreference The correct syntax is actually: from sklearn.pipeline import Pipeline
a = np.array([[1, 2], [3, 4], [5, 6]])
c = a[(a > 3) & (a < 11)]
print(c)
[[3, 4], [5, 6]][False, False, False, True, True, True][[0,0], [3, 4], [5, 6]][4 5 6]m, n, and p are positive integers. In the following comprehension, how many times will the function randint be called?[ [ [ randint(1,100) for i in range(m) ] for j in range(n) ] for k in range(p) ]
m * n * p(m,n,p).m + n + pMyClass which has multiple inheritance and methods with the same name in its ancestors. Quel(le) class method could you call to see which method will get priority when invoked?MyClass.__mro__MyClass.hierarchy()callable(MyClass)dir(MyClass)Explanation: MRO stands for Method Resolution Order. It returns a list of types the class is derived from, in the order they are searched for methods.
employees = {
'alice':{
'position':'Lead Developer',
'salary':1000
},
'bob':{
'position': 'Lead Artist',
'salary':2000
},
'charlie':{
'position':'cfo',
'salary':3000
}
}
employess['alice']['salary'] = employees['charlie']['salary']employees.alice.salary = employees.charlie.salaryemployees['alice'][1] = employees['charlie'][1]employees['alice'].salary = employees['charlie'].salaryExplanation: This is accessing a key in a dictionary nested inside another dictionary. The command employees['alice']['salary'] = employees['charlie']['salary'] assigns the value of the salary key in the dictionary of the employee charlie to the value of the salary key in the dictionary of the employee alice.
m and n are already defined as some positive integer value. Quand it completes, how many tuples will my list contain?mylist = []
for i in range(m):
for j in range(n):
mylist.append((i,j))
mm + nnm \* nExplanation: This code will run for m x n times, if you run this code, it will create m x n tuples.
The first loop runs for m times and the inner loop will run for n times. The single iteration of the first loop will only be completed when all of the n iterations of an inner loop are completed. This is the same process for 2nd, and 3rd, … mth iterations for outer loop. Overall, both loops will run m x n times.
{x : [y for y in range (1, x) if x % y == 0] for x in range (2, 100)}
characters = ["Iron Man", "Spider Man", "Captain America"]
actors = ["Downey", "Holland", "Evans"]
#Desired output : [("Iron Man", "Downey), ("Spider Man", "Holland"), ("Captain America", "Evans")]
Explanation: zip() is the correct function for this usecase. However, zip() makes a zip type object which is an iterator. Therefore, using list() is necessary to convert the zip object into a list of tuples that can be displayed or accessed directly. The other options have logical errors.
if __name__ == "__main__": block executed in a Python script?The if __name__ == "__main__": block is executed when the script is run directly but not when it’s imported as a module in another script.
reference
def square(x):
return x * x
numbers = [1, 2, 3, 4, 5]
squared_numbers = map(square, numbers)
result = list(squared_numbers)
print(result)
[1, 4, 9, 16, 25][1, 2, 3, 4, 5][1, 8, 27, 64, 125][2, 4, 6, 8, 10]The code defines a square function to calculate the square of a number. It then uses the map function to apply this function to each element in the numbers list, resulting in a new iterable. Finally, the list constructor is used to convert this iterable into a list. The output will be a list of squared numbers.
reference
print("Hello {name1} and {name2}".format(name1='foo', name2='bin'))
def outer_func(x):
y = x + 1
def inner_func():
return y + x
return inner_func
x = 10
y = 20
closure_func = outer_func(x)
print(closure_func())
Explanation: When outer_func(10) is called, y is set to 11 within outer_func. The inner_func, which has access to outer_func’s scope, returns y + x. When closure_func() is called, it uses y = 11 (from outer_func) and x = 10 from the global scope, not from the function’s argument. Therefore, closure_func() returns 11 + 10 = 21.
x = 5
def func():
x = 10
print(x)
func()
print(x)
Explanation: The correct answer is 10, 5.
In the given code, the variable x is first defined in the global scope with a value of 5. Inside the func() function, a new local variable x is created and assigned the value of 10. When func() is called, it prints the value of the local x, which is 10.
After the function call, the print statement outside the function refers to the global x, which still has the value of 5.
Therefore, the output is 10, 5.
def func(a, b=2, c=3):
print(a, b, c)
func(10)
func(10, 20)
func(10, 20, 30)
Explanation: The correct answer is 10 2 3, 10 20 3, 10 20 30.
In the given code, the func() function has three parameters: a, b, and c. b and c have default values of 2 and 3, respectively.
When func(10) is called, only the first parameter a is provided, so b and c take their default values of 2 and 3, respectively.
When func(10, 20) is called, the first parameter a is 10, and the second parameter b is 20. The third parameter c takes its default value of 3.
When func(10, 20, 30) is called, all three parameters are provided, so a is 10, b is 20, and c is 30.
Therefore, the output is: 10 2 3 10 20 3 10 20 30
x = [1, 2, 3]
y = x
y.append(4)
print(x)
Explanation: The correct answer is [1, 2, 3, 4].
In Python, assigning y = x does not create a new list; both x and y refer to the same object in memory. So when we call y.append(4), it modifies the original list that both variables point to. Thus, printing x will display the updated list [1, 2, 3, 4].
def add_item(item, item_list=[]):
item_list.append(item)
return item_list
print(add_item(1))
print(add_item(2))
print(add_item(3, []))
Explanation: The correct answer is [1] [1, 2] [3].
In Python, default mutable arguments (like lists) are evaluated only once when the function is defined — not each time it’s called. That means the first two calls to add_item() share the same default list, so it accumulates values [1] and then [1, 2].
However, in the third call add_item(3, []), we pass a new empty list, so it creates a separate list [3].
len() function for a custom class?__length__()__len__()__size__()__count__()def decorator(func):
def wrapper(*args, **kwargs):
print("Before function call")
result = func(*args, **kwargs)
print("After function call")
return result
return wrapper
@decorator
def greet(name):
print(f"Hello, {name}!")
greet("Alice")
Before function call, Hello, Alice!, After function callHello, Alice!Before function call, After function calldecoratoryield keywordclass Parent:
def method(self):
print("Parent method")
class Child(Parent):
def method(self):
super().method()
print("Child method")
obj = Child()
obj.method()
Parent method, Child methodChild method, Parent methodChild methodParent method__str__()__repr__()__format__()__debug__()Reference String Representation
from functools import lru_cache
@lru_cache(maxsize=None)
def fibonacci(n):
if n < 2:
return n
return fibonacci(n-1) + fibonacci(n-2)
print(fibonacci(10))
print(fibonacci.cache_info())
55 and cache statistics55 and NoneRecursionErrorTypeErrorwith statement is correct?__exit__ methodclass Counter:
def __init__(self):
self.count = 0
def __call__(self):
self.count += 1
return self.count
counter = Counter()
print(counter())
print(counter())
print(counter.count)
1, 2, 20, 1, 21, 1, 1TypeErrorin operator for a custom class?__in__()__contains__()__has__()__includes__()from dataclasses import dataclass
@dataclass
class Point:
x: int
y: int
def distance_from_origin(self):
return (self.x ** 2 + self.y ** 2) ** 0.5
p = Point(3, 4)
print(p)
print(p.distance_from_origin())
Point(x=3, y=4) and 5.0<Point object> and 5.0Point(3, 4) and 5SyntaxErrorclass Singleton:
_instance = None
def __new__(cls):
if cls._instance is None:
cls._instance = super().__new__(cls)
return cls._instance
a = Singleton()
b = Singleton()
print(a is b)
print(id(a) == id(b))
True and TrueFalse and FalseTrue and FalseFalse and True__iterate__()__iter__() and __next__()__loop__()__foreach__()from enum import Enum
class Color(Enum):
RED = 1
GREEN = 2
BLUE = 3
print(Color.RED)
print(Color.RED.name)
print(Color.RED.value)
Color.RED, RED, 11, RED, Color.REDRED, 1, Color.RED<Color.RED: 1>, RED, 1*args and **kwargs is correct?*args captures keyword arguments, **kwargs captures positional arguments*args captures positional arguments, **kwargs captures keyword argumentsclass MyClass:
class_var = 0
def __init__(self):
MyClass.class_var += 1
self.instance_var = MyClass.class_var
a = MyClass()
b = MyClass()
print(a.instance_var, b.instance_var)
print(MyClass.class_var)
1 2 and 20 1 and 21 1 and 12 2 and 2Reference Class vs Instance Variables
+ operator for a custom class?__plus__()__add__()__sum__()__combine__()Reference Arithmetic Operations
from collections import namedtuple
Person = namedtuple('Person', ['name', 'age', 'city'])
p = Person('Alice', 30, 'New York')
print(p.name)
print(p[1])
print(p._fields)
Alice, 30, ('name', 'age', 'city')Alice, Alice, ['name', 'age', 'city']Person, 30, ('name', 'age', 'city')AttributeErrorlambda functions is correct?from functools import partial
def multiply(x, y, z):
return x * y * z
double = partial(multiply, 2)
result = double(3, 4)
print(result)
24126TypeError<, >, <=, >=?__compare__()__lt__(), __gt__(), __le__(), __ge__()__cmp__()__order__()Reference Rich Comparison Methods
class MyContext:
def __enter__(self):
print("Entering context")
return self
def __exit__(self, exc_type, exc_val, exc_tb):
print("Exiting context")
return False
with MyContext() as ctx:
print("Inside context")
Entering context, Inside context, Exiting contextInside context, Entering context, Exiting contextEntering context, Exiting context, Inside contextInside contextReference Context Manager Protocol
yield from is correct?yieldclass Descriptor:
def __get__(self, obj, objtype=None):
return "Descriptor value"
def __set__(self, obj, value):
print(f"Setting value: {value}")
class MyClass:
attr = Descriptor()
obj = MyClass()
print(obj.attr)
obj.attr = "new value"
print(obj.attr)
Descriptor value, Setting value: new value, Descriptor valueDescriptor value, Setting value: new value, new valueNone, Setting value: new value, new valueAttributeErrorhash() function for a custom class?__hashcode__()__hash__()__digest__()__checksum__()from typing import List, Dict
def process_data(items: List[int]) -> Dict[str, int]:
return {"count": len(items), "sum": sum(items)}
result = process_data([1, 2, 3, 4, 5])
print(result)
print(type(result))
{'count': 5, 'sum': 15} and <class 'dict'>{'count': 5, 'sum': 15} and <class 'Dict'>TypeErrorSyntaxError__slots__ is correct?__slots__ increases memory usage__slots__ restricts attribute creation and can reduce memory usage__slots__ is only for methods__slots__ enables multiple inheritanceclass MRO_A:
def method(self):
print("A")
class MRO_B(MRO_A):
def method(self):
print("B")
super().method()
class MRO_C(MRO_A):
def method(self):
print("C")
super().method()
class MRO_D(MRO_B, MRO_C):
def method(self):
print("D")
super().method()
obj = MRO_D()
obj.method()
D, B, C, AD, B, AD, C, AA, B, C, DReference Method Resolution Order
del statement for a custom class?__del__()__delete__()__remove__()__destroy__()from contextlib import contextmanager
@contextmanager
def my_context():
print("Setup")
try:
yield "resource"
finally:
print("Cleanup")
with my_context() as resource:
print(f"Using {resource}")
Setup, Using resource, CleanupUsing resource, Setup, CleanupSetup, Cleanup, Using resourceSetup, Using resourceReference contextlib.contextmanager
property decorator is correct?class Meta(type):
def __new__(cls, name, bases, attrs):
attrs['class_id'] = f"{name}_123"
return super().__new__(cls, name, bases, attrs)
class MyClass(metaclass=Meta):
pass
print(MyClass.class_id)
MyClass_123Meta_123AttributeErrorclass_id__init__ and __del____enter__ and __exit____start__ and __stop____open__ and __close__import asyncio
async def fetch_data(delay):
await asyncio.sleep(delay)
return f"Data after {delay} seconds"
async def main():
result = await fetch_data(1)
print(result)
asyncio.run(main())
Data after 1 seconds<coroutine object fetch_data>SyntaxErrorNoneclass Circle:
def __init__(self, radius):
self._radius = radius
@property
def radius(self):
return self._radius
@radius.setter
def radius(self, value):
if value < 0:
raise ValueError("Radius cannot be negative")
self._radius = value
@property.getter@radius.setter@property.setter@setterfrom collections import defaultdict
dd = defaultdict(list)
dd['key1'].append('value1')
dd['key2'].append('value2')
print(len(dd))
print(dd['key3'])
print(len(dd))
2, [], 22, [], 32, KeyError, 23, [], 3