any() on a list?any() function will randomly return any item from the list.any() function returns True if any item in the list evaluates to True. Otherwise, it returns False.any() function takes as arguments the list to check inside, and the item to check for. If “any” of the items in the list match the item to check for, the function returns True.any() function returns a Boolean value that answers the question “Are there any items in this list?”example
if any([True, False, False, False]) == True:
print('Yes, there is True')
>>> 'Yes, there is True'
None.if/else statement, used when testing for equality between objects.Explanation: Attributes are defined under the class, and arguments go under the functions. arguments usually refer to parameters, whereas attributes are the constructors of the class or an instance of a class.
count, fruit, price = (2, 'apple', 3.5)
.delete() methodpop(my_list)del(my_list).pop() methodexample
my_list = [1,2,3]
my_list.pop(0)
my_list
>>>[2,3]
sys library?class Game(LogicGame): passdef Game(LogicGame): passdef Game.LogicGame(): passclass Game.LogicGame(): passExplanation: The parent class which is inherited is passed as an argument to the child class. Therefore, here the first option is the right answer.
def sum(a, b):
"""
sum(4, 3)
7
sum(-4, 5)
1
"""
return a + b
def sum(a, b):
"""
>>> sum(4, 3)
7
>>> sum(-4, 5)
1
"""
return a + b
def sum(a, b):
"""
# >>> sum(4, 3)
# 7
# >>> sum(-4, 5)
# 1
"""
return a + b
def sum(a, b):
###
>>> sum(4, 3)
7
>>> sum(-4, 5)
1
###
return a + b
Explanation: Use ''' to start the doc and add the output of the cell after >>>
setlistNonedictionaryYou can only build a stack from scratch.college_years = ['Freshman', 'Sophomore', 'Junior', 'Senior']
return list(enumerate(college_years, 2019))
[('Freshman', 2019), ('Sophomore', 2020), ('Junior', 2021), ('Senior', 2022)][(2019, 2020, 2021, 2022), ('Freshman', 'Sophomore', 'Junior', 'Senior')][('Freshman', 'Sophomore', 'Junior', 'Senior'), (2019, 2020, 2021, 2022)][(2019, 'Freshman'), (2020, 'Sophomore'), (2021, 'Junior'), (2022, 'Senior')]self means that no other arguments are required to be passed into the method.self method; it’s just historic computer science jargon that Python keeps to stay consistent with other programming languages.self refers to the instance whose method was called.self refers to the class that was inherited from to create the object using self.Simple example
class my_secrets:
def __init__(self, password):
self.password = password
pass
instance = my_secrets('1234')
instance.password
>>>'1234'
namedtuple members and refer to them that way, similarly to how you would access keys in dictionary.tuple.namedtuples are just as memory efficient as regular tuples.namedtuples because they are available in the standard library.We need to import it using:from collections import namedtuple
None.my_game = class.Game()my_game = class(Game)my_game = Game()my_game = Game.create()map() function do?Explanation: - The syntax for map() function is list(map(function,iterable)). The simple area finder using a map would be like this
import math
radius = [1,2,3]
area = list(map(lambda x: round(math.pi*(x**2), 2), radius))
area
>>> [3.14, 12.57, 28.27]
None.True.reference. When the return statement is None or has no value or there is no return statement the function returns None.
pass statement in Python?yield statement of a generator and return a value of None.while or for loop and return to the start of the loop.The pass statement is used as a placeholder for future code. When the pass statement is executed, nothing happens, but you avoid getting an error when empty code is not allowed. reference
slotdictionaryqueuesorted listfruits = ['Apples', 'Oranges', 'Bananas']
quantities = [5, 3, 4]
prices = [1.50, 2.25, 0.89]
#Desired output
[('Apples', 5, 1.50),
('Oranges', 3, 2.25),
('Bananas', 4, 0.89)]
output = []
fruit_tuple_0 = (first[0], quantities[0], price[0])
output.append(fruit_tuple)
fruit_tuple_1 = (first[1], quantities[1], price[1])
output.append(fruit_tuple)
fruit_tuple_2 = (first[2], quantities[2], price[2])
output.append(fruit_tuple)
return output
i = 0
output = []
for fruit in fruits:
temp_qty = quantities[i]
temp_price = prices[i]
output.append((fruit, temp_qty, temp_price))
i += 1
return output
groceries = zip(fruits, quantities, prices)
return groceries
>>> [
('Apples', 5, 1.50),
('Oranges', 3, 2.25),
('Bananas', 4, 0.89)
]
i = 0
output = []
for fruit in fruits:
for qty in quantities:
for price in prices:
output.append((fruit, qty, price))
i += 1
return output
all() function returns a Boolean value that answers the question “Are all the items in this list the same?all() function returns True if all the items in the list can be converted to strings. Otherwise, it returns False.all() function will return all the values in the list.all() function returns True if all items in the list are evaluated to True. Otherwise, it returns False.Explanation: all() returns True if all in the list are True. See example below:
test = [True, False, False, False]
if all(test) is True:
print('Yeah, all of them are true.')
else:
print('There is an imposter.')
>>> 'There is an imposter'
(Answer format may vary. Game and roll (or dice_roll) should each be called with no parameters.)
>>> dice = Game()
>>> dice.roll()
>>> dice = Game(self)
>>> dice.roll(self)
>>> dice = Game()
>>> dice.roll(self)
>>> dice = Game(self)
>>> dice.roll()
Both merge sort and quicksort employ a common algorithmic paradigm based on recursion. This paradigm, divide-and-conquer, breaks a problem into subproblems that are similar to the original problem, recursively solves the subproblems, and finally combines the solutions to the subproblems to solve the original problem. reference
.append() method?This function has constant time complexity i.e. O(1), because lists are randomly accessed so the last element can be reached in O(1) time that’s why the time taken to add the new element at the end of the list is O(1).
set and a list?Abstraction in Python is defined as a process of handling complexity by hiding unnecessary information from the user. reference
def print_alpha_nums(abc_list, num_list):
for char in abc_list:
for num in num_list:
print(char, num)
return
print_alpha_nums(['a', 'b', 'c'], [1, 2, 3])
a 1
a 2
a 3
b 1
b 2
b 3
c 1
c 2
c 3
['a', 'b', 'c'], [1, 2, 3]
aaa
bbb
ccc
111
222
333
a 1 2 3
b 1 2 3
c 1 2 3
def sum(a, b):
# a = 1
# b = 2
# sum(a, b) = 3
return a + b
def sum(a, b):
"""
a = 1
b = 2
sum(a, b) = 3
"""
return a + b
def sum(a, b):
"""
>>> a = 1
>>> b = 2
>>> sum(a, b)
3
"""
return a + b
def sum(a, b):
'''
a = 1
b = 2
sum(a, b) = 3
'''
return a + b
Explanation: Use """ to start and end the docstring and use >>> to represent the input. If you write this correctly you can also run the doctest using the build-in doctest module
Example
# namedtuple function accepts the following arguments to generate a class
from collections import namedtuple
>>> Point = namedtuple('Point',['x','y'])
>>> point = Point(100, 200)
>>> point
Point(x=100, y=200)
# Which lets you use both unpacking and iteration to access
>>> x, y = point
>>> print(f'({x}, {y})')
(100, 200)
>>> for coordinate in point:
print(coordinate)
100
200
&&===||fruit_info = {
'fruit': 'apple',
'count': 2,
'price': 3.5
}
fruit_info['price'] = 1.5my_list[3.5] = 1.51.5 = fruit_info['price]my_list['price'] == 1.55 != 6
yesFalseTrueNoneExplanation: In Python, != is equivalent to not equal to.
__init__() method do?Example:
class test:
def __init__(self):
print('I came here without your permission lol')
pass
t1 = test()
>>> 'I came here without your permission lol'
How many microprocessors it would take to run your code in less than one secondHow many lines of code are in your code fileThe amount of space taken up in memory as a function of the input sizeHow many copies of the code file could fit in 1 GB of memoryfruit_info = {'fruit': 'apple', 'count': 2, 'price': 3.5}fruit_info =('fruit': 'apple', 'count': 2,'price': 3.5 ).dict()fruit_info = ['fruit': 'apple', 'count': 2,'price': 3.5 ].dict()fruit_info = to_dict('fruit': 'apple', 'count': 2, 'price': 3.5)fruits = {'Apples': 5, 'Oranges': 3, 'Bananas': 4}
fruit_names = [x in fruits.keys() for x]fruit_names = for x in fruits.keys() *fruit_names = [x for x in fruits.keys()]fruit_names = x for x in fruits.keys()self keyword when defining or calling methods on an instance of an object?self refers to the class that was inherited from to create the object using self.self method. It’s just legacy computer science jargon that Python keeps to stay consistent with other programming languages.self means that no other arguments are required to be passed into the method.self refers to the instance whose method was called.Explanation: - Try running the example of the Q42 without passing self argument inside the __init__, you’ll understand the reason. You’ll get the error like this __init__() takes 0 positional arguments but 1 was given, this means that something is going inside even if it hasn’t been specified, which is the instance itself.
Reference
Class methods are methods that are called on the class itself, not on a specific object instance. Therefore, it belongs to a class level, and all class instances share a class method.
def getMaxNum(list_of_nums): # body of function goes herefunc get_max_num(list_of_nums): # body of function goes herefunc getMaxNum(list_of_nums): # body of function goes heredef get_max_num(list_of_nums): # body of function goes hereThe use of underscores as word separators dates back to the late 1960s. It is particularly associated with C, is found in The C Programming Language (1978), and contrasted with the Pascal case (a type of camel case). However, the convention traditionally had no specific name: the Python programming language style guide refers to it simply as “lowercase_with_underscores”.[2] Within Usenet the term snake_case was first seen in the Rubycommunity in 2004,[3] used by Gavin Kistner, writing: BTW…what _do you call that naming style? snake_case? That’s what I’ll call it until someone corrects me.
maxValue = 255max_value = 255MAX_VALUE = 255MaxValue = 255Use an uppercase single letter, word, or words. Separate words with underscores to improve readability. Reference
Deque or Double Ended Queue is a generalized version of the Queue data structure that allows inserting and deletion at both ends. reference
my_set = {0, 'apple', 3.5}my_set = to_set(0, 'apple', 3.5)my_set = (0, 'apple', 3.5).to_set()my_set = (0, 'apple', 3.5).set()__init__() method that takes no parameters?class __init__(self):
pass
def __init__():
pass
class __init__():
pass
def __init__(self):
pass
In computer science, a binary search tree (BST), also called an ordered or sorted binary tree, is a rooted binary tree data structure with the key of each internal node being greater than all the keys in the respective node’s left subtree and less than the ones in its right subtree. reference
Decorators allow us to wrap another function to extend the behavior of the wrapped function, without permanently modifying it. reference
def tax(my_float):
''' Calculates the sales tax of a purchase. Takes in a float representing the subtotal as an argument and returns a float representing the sales tax.'''
pass
def tx(amt):
''' Gets the tax on an amount.'''
def sales_tax(amount):
''' Calculates the sales tax of a purchase. Takes in a float representing the subtotal as an argument and returns a float representing the sales tax.'''
def calculate_sales_tax(subtotal):
pass
mixin?mixin to force a function to accept an argument at runtime even if the argument wasn’t included in the function’s definition.mixin to allow a decorator to accept keyword arguments.mixin to make sure that a class’s attributes and methods don’t interfere with global variables and functions.mixin to define that functionality.There are two main situations where mixins are used: You want to provide a lot of optional features for a class. You want to use one particular feature in a lot of different classes. reference explanation
Explanation: Stack uses the last in first out approach.
with keyword?with keyword lets you choose which application to open the file in.with keyword acts like a for loop, and lets you access each line in the file one by one.with keyword for opening a file in Python.with keyword in Python, Python will make sure the file gets closed, even if an exception or error is thrown.It is good practice to use the ‘with’ keyword when dealing with file objects. The advantage is that the file is properly closed after its suite finishes, even if an exception is raised at some point. Using with is also much shorter than writing equivalent try-finally blocks:
example
>>> f = open('workfile', 'w', encoding="utf-8")
>>> with open('workfile', encoding="utf-8") as f:
read_data = f.read()
# We can check that the file has been automatically closed.
>>> f.closed
True
python3 -m doctest <_filename_>python3 <_filename_>python3 <_filename_> rundoctestspython3 doctestThere is also a command line shortcut for running testmod(). You can instruct the Python interpreter to run the doctest module directly from the standard library and pass the module name(s) on the command line:
python -m doctest -v example.py
This will import example.py as a standalone module and run testmod() on it. Note that this may not work correctly if the file is part of a package and imports other submodules from that package.
reference
tutorial video
Explanation:
The lambda notation is an anonymous function that can take any number of arguments with only a single expression (i.e., cannot be overloaded). It has been introduced in other programming languages, such as C++ and Java. The lambda notation allows programmers to “bypass” function declaration.
def get_next_card():
# method body goes here
def get_next_card(self):
# method body goes here
def self.get_next_card():
# method body goes here
def self.get_next_card(self):
# method body goes here
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])-- This is a comment# This is a comment/* This is a comment */// This is a commentapple in the list with the string orange?my_list = ['kiwi', 'apple', 'banana']
orange = my_list[1]my_list[1] = 'orange'my_list['orange'] = 1my_list[1] == orangeTypical queue definition follows “first-in, first out” (FIFO) where items are enqueued on one-side and dequeued from the other. Reference
num_people = 5
if num_people > 10:
print("There is a lot of people in the pool.")
elif num_people > 4:
print("There are some people in the pool.")
else:
print("There is no one in the pool.")
num_people = 5
if num_people > 10:
print("There is a lot of people in the pool.")
if num_people > 4:
print("There are some people in the pool.")
else:
print("There is no one in the pool.")
num_people = 5
if num_people > 10;
print("There is a lot of people in the pool.")
elif num_people > 4;
print("There are some people in the pool.")
else;
print("There is no one in the pool.")
if num_people > 10;
print("There is a lot of people in the pool.")
if num_people > 4;
print("There are some people in the pool.")
else;
print("There is no one in the pool.")
defaultdict work?defaultdict will automatically create a dictionary for you that has keys which are the integers 0-10.defaultdict forces a dictionary to only accept keys that are of the types specified when you created the defaultdict (such as strings or integers).defaultdict with a nonexistent key, a new default key-value pair will be created for you instead of throwing a KeyError.defaultdict stores a copy of a dictionary in memory that you can default to if the original gets unintentionally modified.defaultdict is a container-like dictionary present in the module collections. The functionality of both dictionaries and defaultdict are almost the same except for the fact that defaultdict never raises a KeyError. It provides a default value for the key that does not exist.
example
# Function to return a default
# values for keys that are not
# present
def def_value():
return "Not Present"
# Defining the dict
d = defaultdict(def_value)
variety to the fruit_info dictionary that has a value of Red Delicious?fruit_info['variety'] == 'Red Delicious'fruit_info['variety'] = 'Red Delicious'red_delicious = fruit_info['variety']red_delicious == fruit_info['variety']while loop?Simple Example
i = 1
while i<6:
print(f"Countdown: {i}")
i = i + 1
__init__() method that sets instance-specific attributes upon creation of a new class instance?def __init__(self, attr1, attr2):
attr1 = attr1
attr2 = attr2
def __init__(attr1, attr2):
attr1 = attr1
attr2 = attr2
def __init__(self, attr1, attr2):
self.attr1 = attr1
self.attr2 = attr2
def __init__(attr1, attr2):
self.attr1 = attr1
self.attr2 = attr2
Explanation:: When instantiating a new object from a given class, the __init__() method will take both attr1 and attr2, and set its values to their corresponding object attribute, that’s why the need of using self.attr1 = attr1 instead of attr1 = attr1.
def count_recursive(n=1):
if n > 3:
return
print(n)
count_recursive(n + 1)
1
1
2
2
3
3
3
2
1
3
3
2
2
1
1
1
2
3
Intersect; union|; &&; |&&; ||import numpy as np
np.ones([1,2,3,4,5])
open function. What might be the easiest solution?PATH.PYTHONPATH environment variable.{x for x in range(100) if x%3 == 0}
reference It is a Set Comprehension because in ‘{}’, curly brackets, so it will return a ‘Set`!
datetimedatedaydaytimetimedatedef Game(): passdef Game: passclass Game: passclass Game(): passmy_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)a = np.array([1,2,3,4])
print(a[[False, True, False, False]])
{0,2}[2]{2}[0,2,0,0]z = y.split(';')
len(z)
Explanation::
y="stuff;thing;junk"
len(z) ==> 3
y="stuff;thing;junk;"
len(z) ==> 4
num_list = [1,2,3,4,5]
num_list.remove(2)
print(num_list)
[1,2,4,5][1,3,4,5][3,4,5][1,2,3]Explanation:: .remove() is based on the value of the item, not the index; here, it is removing the item matching “2”. If you wanted to remove an item based on its index, you would use .pop().
num_list = [1,2,3,4,5]
num_list.pop(2)
>>> [1,2,4,5]
num_list.remove(2)
>>> [1,3,4,5]
[10,9,8,7,6,5,4,3,2,1]
reversed(list(range(1,11)))list(reversed(range(1,10)))list(range(10,1,-1))list(reversed(range(1,11)))import math
print(math.pow(2,10)) # prints 2 elevated to the 10th power
print(2^10)
print(2**10)
y = [x*2 for x in range(1,10)]
print(y)
y = 1
for i in range(1,10):
y = y * 2
print(y)
[] are _, {} are _, and () are _.table = np.array([
[1,3],
[2,4]])
print(table.max(axis=1))
[2, 4][3, 4][4][1,2]number = 3
print(f"The number is {number}")
The number is 3the number is 3THE NUMBER IS 3TypeError because the integer must be cast to a string.my_tuple tup(2, 'apple', 3.5) %Dmy_tuple [2, 'apple', 3.5].tuple() %Dmy_tuple = (2, 'apple', 3.5)my_tuple = [2, 'apple', 3.5]write('w')scan('s')append('a')read('r')setlisttupledictionarysys.exc_info()os.system()os.getcwd()sys.executablemy_dictionary = {
'A': 1,
'B': 2,
'C': 3,
'D': 4,
'E': 5
}
letters = []
for letter in my_dictionary.values():
letters.append(letter)
letters = my_dictionary.keys()letters = [letter for (letter, number) in my_dictionary.items()]letters4 = list(my_dictionary)Explanation: The first one (the correct option) returns the list of the values (the numbers). The rest of the options return a list of the keys.
print function. What function can you use within NumPy to force it to print the entire array?set_printparamsset_printoptionsset_fullprintsetp_printwholetry/except blocks when you want to run some code, but need a way to execute different code if an exception is raised.try/except blocks inside of unit tests so that the unit tests will always pass.try/except blocks so that you can demonstrate to your code reviewers that you tried a new approach, but if the new approach is not what they were looking for, they can leave comments under the except keyword.try/except blocks so that none of your functions or methods return None.because of the level of indentation after the for loopbecause of the end keyword at the end of the for loopbecause the block is surrounded by brackets ({})because of the blank space at the end of the body of the for loopsys.stdoutx after running this code?x = {1,2,3,4,5}
x.add(5)
x.add(6)
{1, 2, 3, 4, 5, 5, 6}{5, 6, 1, 2, 3, 4, 5, 6}{6, 1, 2, 3, 4, 5}{1, 2, 3, 4, 5, 6}Explanation: The .add() method adds the element to the set only if it doesn’t exist.
fruit_info = {
'fruit': 'apple',
'count': 2,
'price': 3.5
}
my_keys = fruit_info.to_keys()my_keys = fruit_info.all_keys()my_keys = fruit_info.keysmy_keys = fruit_info.keys()def be_friendly(greet = "How are you!", name):
pass
name is a reserved word.np, which choice will return True?a = np.zeros([3,4])
b = a.copy()
np.array_equal(a,b)
a = np.empty([3,4])
b = np.empty([3,4])
np.array_equal(a,b)
a = np.zeros([3,4])
b = np.zeros([4,3])
np.array_equal(a,b)
a = np.array([1, np.nan])
np.array_equal(a,a)
// This is a comment# This is a comment-- This is a comment/* This is a comment *\import numpy as np
a = np.array([1,2,3])
b = np.array([4,5,6])
c = a*b
d = np.dot(a,b)
c = [ a[1] * b[1], a[2] * b[2], a[3] * b[3] ]
d = sum(c)
c = a[0] * b[0], a[1] * b[1], a[2] * b[2]
d = [ a[0] * b[0], a[1] * b[1], a[2] * b[2] ]
c = [ a[0] * b[0], a[1] * b[1], a[2] * b[2] ]
d = sum(a) + sum(b)
c = [ a[0] * b[0], a[1] * b[1], a[2] * b[2] ]
d = sum(c)
linalg.eig() and .matmul()linalg.inv() and .dot()linalg.det() and .dot()linalg.inv() and .eye()Explanation: Understanding this answer requires knowledge of linear algebra. Some systems of equations can be solved by the method of diagonalization, which involves finding the eigenvectors and eigenvalues of the system’s matrix and multiplying related matrices.
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)num_list = [21, 13, 19, 3, 11, 5, 18]
num_list.sort()
num_list[len(num_list) // 2]
Explanation: // is the operator for floor division, which is a normal division operation that returns the largest possible integer, either less than or equal to the normal division result. Here it is used to find the median, which is the value separating the higher half from the lower half of a data sample, by finding the index of the list item in the middle of the list. (This is sufficient for a list with an odd number of items; if the list had an even number of items, you would average the values of the two middle items to find the median value.)
vector of type np.array with 10,000 elements. How can you turn vector into a variable named matrix with 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)Explanation: The titanic['Survived'] returns a pandas.Series object, which contains the Survived column of the DataFrame.
Adding the values of this column (i.e. sum(titanic['Survived'])) returns the total number of survivors since a survivor is represented by a 1 and a loss by 0.
characters = ["Iron Man", "Spider Man", "Captain America"]
actors = ["Downey", "Holland", "Evans"]
# example output : [("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 as a key, and x squared as its value; from 1 to 100.x as a key, and x squared as its value; from 1 to 99.x, x squared); from 1 to 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], what is the value of numbers[-2]?_init_() method that takes no parameters?def*init*(self): passclass*init*(self): passclass*init*(): passdef*init*(): pass() - empty parameter.
self - refers to all instances within a class.
_init_ - a reserved method, AKA a constructor.
_init_() - always executed when the class is being initiated.
sin function from the math library. What is the correct syntax for importing only that function?using math.sinimport math.sinfrom math import sinimport sin from mathExplanation: The from..import statement allows you to import specific functions/variables from a module instead of importing everything.
0the count of all True valuesa type errorNoneprint("foo" if (256).bit_length() > 8 else "bar")
TruefoobarTrue.RuntimeError if you do not return a value.None.tabular; numerical
gcc or clang.pip or conda.
random.uniform(0,50);plt.histrandom.gauss(50,20);plt.histrandom();plt.scatterrandom.triangular(0,50);plt.bara and b?import numpy as np
a = np.arange(100)
b = a[50:60:2]
a: all integers from 0 to 99 (inclusive); b: all even integers from 50 to 58 (inclusive).a: all integers from 0 to 100 (inclusive); b: all even integers from 50 to 60 (inclusive).a: all integers from 0 to 99 (inclusive); b: all even integers from 50 to 60 (inclusive).a: all integers from 0 to 99 (inclusive); b: all odd integers from 49 to 59 (inclusive).my_object?my_object.get_shape()my_object.shapemy_object.dim()len(my_object)mylist and you want to search for a specific value. The minimum number of comparisons will be __ and the maximum number of comparisons will be _?len(mylist); len(mylist)1; len(mylist)2; len(mylist)0; len(mylist)Explanation: Can use a break statement and the value being searched can be the first element of the list, given that it is non-empty.
0TrueNoneFalseimport numpy as np
def can_matrices_be_multiplied (matrix1, matrix2):
rowsMat1, columnsMat1 = matrix1.shape
rowsMat2, columnsMat2 = matrix2.shape
if _____ == ______ :
print("The matrices can be multiplied!")
return True
else:
return False
reference. A matrix can be multiplied by any other matrix that has the same number of rows as the first columns. I.E. A matrix with 2 columns can be multiplied by any matrix with 2 rows
[(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()
Explanation: In the first, super does not have .name (should be self.name). The third drops Robert, and base is not defined in the 4th.
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']
[]
Explanation: Dictionaries usually result in an exception when using the square bracket syntax. Defaultdict here returns a default value dedicated by the first parameter so instead of throwing an exception, they return the default. Note that this needs to be imported as follows: from collections import defaultdict
n is already defined as any positive integer value.)[x*2 for x in range(1,n)]
x = 18
if x > 10:
if x > 15:
print('A')
else:
print('B')
else:
print('C')
reference No No fixed length is specified but Pep-8 specifies under “Maximum Line Length” to “Limit all lines to a maximum of 79 characters”.
i variable be when the following loop finishes its execution?for i in range(5): pass
f-strings are also called:Explanation:: Python threading is restricted to a single CPU at one time. The multiprocessing library will allow you to run code on different processors.
y in this code?x = 5
y = 1 + (20 if x < 5 else 30)
False21231Explanation: If you have only one statement to execute, one for if and one for else, you can put it all on the same line.
x = 5
# This is the same statement expanded to multiple lines
y = 1
if (x < 5):
y += 20
else:
y += 30
reference
“Pickling” is the process whereby a Python object hierarchy is converted into a byte stream, and “unpickling” is the inverse operation, whereby a byte stream (from a binary file or bytes-like object) is converted back into an object hierarchy.
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. Which 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. When 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