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
None
.if/else
statement, used when testing for equality between objects.Explanation Attributes defined under the class, arguments goes under the functions. arguments usually refer as parameter, whereas attributes are the constructor of the class or an instance of a class.
count, fruit, price = (2, 'apple', 3.5)
tuple assignment
tuple unpacking
tuple matching
tuple duplication
.delete()
methodpop(my_list)
del(my_list)
.pop()
methodexample
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.
Explanation - use '''
to start the doc and add output of the cell after >>>
set
list
None
dictionary
You can only build a stack from scratch.
[('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
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 synax for map()
function is list(map(function,iterable))
. The simple area finder using map would be like this
None
.True
.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.slot
dictionary
queue
sorted list
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 evaluate to True. Otherwise, it returns False.Explanation - all()
returns true if all in the list are True, see example below
(Answer format may vary. Game and roll (or dice_roll) should each be called with no parameters.)
.append()
method?set
and a list
?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 build-in doctest module
Example
&&
=
==
||
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 - !=
is equivalent to not equal to in python
__init__()
method do?Example:
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 haven't specified, which is instance itself.
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
maxValue = 255
max_value = 255
MAX_VALUE = 255
MaxValue = 255
Explanation - deque
is used to create block chanin and in that there is first in first out approch, which means the last element to enter will be the first to leave.
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?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.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.python3 -m doctest <_filename_>
python3 <_filename_>
python3 <_filename_> rundoctests
python3 doctest
Explanation:
The lambda notation is basically an anonymous function that can take any number of arguments with only single expression (i.e, cannot be overloaded). It has been introducted in other programming languages, such as C++ and Java. The lambda notation allows programmers to "bypass" function declaration.
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
orange = my_list[1]
my_list[1] = 'orange'
my_list['orange'] = 1
my_list[1] == orange
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.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
__init__()
method that sets instance-specific attributes upon creation of a new class instance?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
.
Intersect
; union
|
; &
&
; |
&&
; ||
open
function. What might be the easiest solution?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)
{0,2}
[2]
{2}
[0,2,0,0]
Explanation:
[1,2,4,5]
[1,3,4,5]
[3,4,5]
[1,2,3]
Explanation:
[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)))
[]
are _, {}
are _, and ()
are _.[2, 4]
[3, 4]
[4]
[1,2]
The number is 3
the number is 3
THE NUMBER IS 3
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
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 testes 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 of the block is surrounded by brackets ({})
because of the blank space at the end of the body of the for loop
{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.
my_keys = fruit_info.to_keys()
my_keys = fruit_info.all_keys()
my_keys = fruit_info.keys
my_keys = fruit_info.keys()
name
is a reserved word.np
, which choice will return True
?// This is a comment
# This is a comment
-- This is a comment
/* This is a comment *\
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)
Explanation: The median is the value separating the higher half from the lower half of a data sample. Here it is 13.
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)
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.
[(x,y)] for x in characters for y in actors]
zip(characters, actors)
[ ]
{x:y for x in characters for y in actors}
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)
[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]
?() -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
0
the count of all True values
a type error
None
random.uniform(0,50);plt.hist
random.gauss(50,20);plt.hist
random();plt.scatter
random.triangular(0,50);plt.bar
my_object.get_shape()
my_object.shape
my_object.dim()
len(my_object)
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.
[(x, x+1) for x in range(1,5)]
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.
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
for i in range(5): pass
Explanation: Python threading is restricted to a single CPU at one time. The multiprocessing library will allow you to run code on different processors.
Explanation:
If x < 5 ==> y = 1 + 20
Else y = 1 + 30
Explanation: Pickling is the process of sterilizing a Python object, that is, conversion of a byte stream into Python object hierarchy. The reverse of this process is known as unpickling.
print("programming".center())
j
has not been initializedExplanation: 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
.
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.
Which of the following choices are the missing arguments?
[[3, 4], [5, 6]]
[False, False, False, True, True, True]
[[0,0], [3, 4], [5, 6]]
[4 5 6]
apple
in the list with the string orange
?orange = my_list[1]
my_list[1] = 'orange'
my_list['orange'] = 1
my_list[1] == orange
randint
be called?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.
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 nested dictionary 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 'salary' key in the dictionary of the employee 'alice'.
It is the same thing as:
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. While the single iteration of first loop will only be completed when all of the n iterations of inner loop are completed. This is the same process for 2nd, 3rd, … mth iterations for outer loop. Overall, both loops will run m x n times