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()
method pop(my_list)
del(my_list)
.pop()
method example
my_list = [1,2,3] my_list.pop(0) my_list >>>[2,3]
sys
library?class Game(LogicGame): pass
def Game(LogicGame): pass
def Game.LogicGame(): pass
class Game.LogicGame(): pass
Explanation: 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 >>>
set
list
None
dictionary
You 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
slot
dictionary
queue
sorted list
fruits = ['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 output. 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.5
my_list [3.5] = 1.5
1.5 = fruit_info ['price]
my_list['price'] == 1.5
5 != 6
yes
False
True
None
Explanation: 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 second
How many lines of code are in your code file
The amount of space taken up in memory as a function of the input size
How many copies of the code file could fit in 1 GB of memory
fruit_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 here
func get_max_num(list_of_nums): # body of function goes here
func getMaxNum(list_of_nums): # body of function goes here
def get_max_num(list_of_nums): # body of function goes here
The 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 = 255
max_value = 255
MAX_VALUE = 255
MaxValue = 255
Use 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_> rundoctests
python3 doctest
There 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 comment
apple
in the list with the string orange
?my_list = ['kiwi', 'apple', 'banana']
orange = my_list[1]
my_list[1] = 'orange'
my_list['orange'] = 1
my_list[1] == orange
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('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`!
datetime
dateday
daytime
timedate
def Game(): pass
def Game: pass
class Game: pass
class Game(): pass
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)
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 3
the number is 3
THE NUMBER IS 3
TypeError
because the integer must be cast to a string. my_tuple tup(2, 'apple', 3.5) %D
my_tuple [2, 'apple', 3.5].tuple() %D
my_tuple = (2, 'apple', 3.5)
my_tuple = [2, 'apple', 3.5]
write('w')
scan('s')
append('a')
read('r')
set
list
tuple
dictionary
sys.exc_info()
os.system()
os.getcwd()
sys.executable
my_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_printparams
set_printoptions
set_fullprint
setp_printwhole
try/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 loop
because of the end keyword at the end of the for loop
because the block is surrounded by brackets ({})
because of the blank space at the end of the body of the for loop
sys.stdout
x
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.keys
my_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("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")]
%OPTION% [(x,y)] for x in characters for y in actors]
%OPTION% zip(characters, actors)
%OPTION%
d = {} for x in range(1, len(characters)): d[x] = actors[x]
%OPTION% {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): pass
class*init*(self): pass
class*init*(): pass
def*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.sin
import math.sin
from math import sin
import sin from math
Explanation: The from..import
statement allows you to import specific functions/variables from a module instead of importing everything.
0
the count of all True values
a type error
None
print ("foo" if (256).bit_length() > 8 else "bar")
True
foo
bar
True
. RuntimeError
if you do not return a value. None
. gcc
or clang
. pip
or conda
. random.uniform(0,50);plt.hist
random.gauss(50,20);plt.hist
random();plt.scatter
random.triangular(0,50);plt.bar
a
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.shape
my_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.
0
True
None
False
import 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("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("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("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("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)
False
21
2
31
Explanation: 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"))
True
1
2
False
print("programming".center())
cr
programming
TypeError: 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. True
1j
False
Explanation: 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)
33
63
0xA + 0xB + 0xC
None
Explanation: 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 Dog
scikit-learn
, import from the scikit-learn._
submodule.preprocessing
pipeline
filters
pipe_filter
reference 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 + p
MyClass
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.salary
employees['alice'][1] = employees['charlie'][1]
employees['alice'].salary = employees['charlie'].salary
Explanation: 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))
m
m + n
n
m \* n
Explanation: 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, ... m
th 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"] #example output : [("Iron Man", "Downey), ("Spider Man", "Holland"), ("Captain America", "Evans")]
d = {}
for x in range(1, len(characters)):
d[x] = actors [x]
for i in range(5):
print (i)
else:
print("Done!")
1
2
3
4
Done!
0
1
3
4
5
Done!
1
3
4
5
Done!
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'))