Python Quistions
Python Quistions
Python Quistions
An abstract class is the name for any class from which you can instantiate
an object.
An abstract class exists only so that other “concrete” classes can inherit
from the abstract class.
reference
Q2. What happens when you use the build-in function any() on a list?
The any() function will randomly return any item from the list.
The any() function returns True if any item in the list evaluates to True.
Otherwise, it returns False.
The 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.
The any() function returns a Boolean value that answers the question “Are
there any items in this list?”
example
Q3. What data structure does a binary tree degenerate to if it isn’t balanced
properly?
linked list
queue
set
OrderedDict
Static methods are called static because they always return None.
Static methods can access and modify the state of a class or an instance of
a class.
reference
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.
Q6. What is the term to describe this code?
tuple assignment
tuple unpacking
tuple matching
tuple duplication
Q7. What built-in list method would you use to remove items from a list?
.delete() method
pop(my_list)
del(my_list)
.pop() method
example
my_list = [1,2,3]
my_list.pop(0)
my_list
>>>[2,3]
Q8. What is one of the most common use of Python’s sys library?
Q10. What is the correct syntax for defining a class called Game, if it inherits
from a parent class called LogicGame?
A
sum(-4, 5)
1
"""
return a + b
B
>>> sum(-4, 5)
1
"""
return a + b
C
# >>> sum(-4, 5)
# 1
"""
return a + b
D
>>> sum(-4, 5)
1
###
return a + b
Explanation - use ''' to start the doc and add output of the cell after >>>
Q12. What built-in Python data type is commonly used to represent a stack?
set
list
None
dictionary
Q14. What is the purpose of the “self” keyword when defining or calling
instance methods?
self means that no other arguments are required to be passed into the
method.
There is no real purpose for the self method; it’s just historic computer
science jargon that Python keeps to stay consistent with other programming
languages.
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'
Instance methods can modify the state of an instance or the state of its
parent class.
An instance method is any class method that doesn’t take any arguments.
A parent class is encapsulated and no data from the parent class passes
on to the child class.
It keeps data and the methods that can manipulate that data in one place.
It runs one chunk of code if all the imports were successful, and another
chunk of code if the imports were not successful.
It tells the computer which chunk of code to run if the is enough memory
to handle it, and which chunk of code to run if there is not enough memory to
handle it.
Q19. What built-in Python data type is best suited for implementing a queue?
dictionary
set
list
Q20. What is the correct syntax for instantiating a new object of the type
Game?
my_game = class.Game()
my_game = class(Game)
my_game = Game()
my_game = Game.create()
Q22. If you don’t explicitly return a value from a function, what happens?
The function will enter an infinite loop because it won’t know when to stop
executing its code.
It is used to skip the rest of a while or for loop and return to the start of
the loop.
Q24. What is the term used to describe items that may be passed into a
function?
arguments
paradigms
attributes
decorators
Q25. Which collection type is used to associate values with unique keys?
slot
dictionary
queue
sorted list
Q27. Assuming the node is in a singly linked list, what is the runtime complexity
of searching for a specific node within a singly linked list?
The runtime is O(n) because in the worst case, the node you are searching
for is the last node, and every node in the linked list must be visited.
The runtime is O(nk), with n representing the number of nodes and k
representing the amount of time it takes to access each node in memory.
The runtime cannot be determined unless you know how many nodes are
in the singly linked list.
The runtime is O(1) because you can index directly to a node in a singly
linked list.
Q28. Given the following three list, how would you create a new list that
matches the desired output printed below?
#Desired output
[('Apples', 5, 1.50),
('Oranges', 3, 2.25),
('Bananas', 4, 0.89)]
output = []
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
>>> [
('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
Q29. What happens when you use the built-in function all() on a list?
The all() function returns a Boolean value that answers the question “Are
all the items in this list the same?
The all() function returns True if all the items in the list can be converted
to strings. Otherwise, it returns False.
The all() function will return all the values in the list.
The 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
test = [True,False,False,False]
if all(test) is True:
print('Yeah all are True')
else:
print('There is an imposter')
>>> 'There is an imposter'
Q30. What is the correct syntax for calling an instance method on a class named
Game?
(Answer format may vary. Game and roll (or dice_roll) should each be called with no
parameters.)
backtracking
dynamic programming
Elements can be retrieved from a list but they cannot be retrieved from a
set.
Abstraction means that a different style of code can be used, since many
details are already known to the program behind the scenes.
Abstraction means the implementation is hidden from the user, and only
the relevant data or information is shown.
Abstraction means that the data and the functionality of a class are
combined into one entity.
Abstraction means that a class can inherit from more than one parent
class.
a 1
a 2
a 3
b 1
b 2
b 3
c 1
c 2
c 3
aaa
bbb
ccc
111
222
333
a 1 2 3
b 1 2 3
c 1 2 3
return a + b
return a + b
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 build-in doctest
module
Q37. Suppose a Game class inherits from two parent classes: BoardGame and
LogicGame. Which statement is true about the methods of an object
instantiated from the Game class?
When instantiating an object, the object doesn’t inherit any of the parent
class’s methods.
Example
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]
Q39. What symbol(s) do you use to assess equality between two elements?
&&
=
==
||
Q40. Review the code below. What is the correct syntax for changing the price
to 1.5?
fruit_info = {
'fruit': 'apple',
'count': 2,
'price': 3.5
}
my_list['price'] == 1.5
5 != 6
yes
False
True
None
It makes classes aware of each other if more than one class is defined in a
single code file.
It initializes any imports you may have included at the top of your file.
Example:
class test:
def __init__(self):
print('I came here without your permission lol')
pass
t1 = test()
>>> 'I came here without your permission lol'
Q43. What is meant by the phrase “space complexity”?
How many microprocessors it would take to run your code in less than
one second
Q44. What is the correct syntax for creating a variable that is bound to a
dictionary?
Q45. What is the proper way to write a list comprehension that represents all
the keys in this dictionary?
Q46. What is the purpose of the 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.
There is no real purpose for the 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.
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.
A class method can modify the state of the class, but they can’t directly
modify the state of an instance that inherits from that class.
You did not use very many advanced computer programming concepts in
your code.
The amount of time it takes the function to complete grows linearly as the
input size increases.
Q49. What is the proper way to define a function?
Q50. According to the PEP 8 coding style guidelines, how should constant
values be named in Python?
A deque adds items to one side and remove items from the other side.
A deque adds items to either or both sides, but only removes items from
the top.
A deque adds items at either or both ends, and remove items at either or
both ends.
A deque adds items only to the top, but remove from either or both sides.
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.
Q52. What is the correct syntax for creating a variable that is bound to a set?
Q53. What is the correct syntax for defining an __init__() method that takes no
parameters?
class __init__(self):
pass
def __init__():
pass
class __init__():
pass
def __init__(self):
pass
Q54. Which of the following is TRUE About how numeric data would be
organised in a binary Search tree?
For any given Node in a binary Search Tree, the child node to the left is
less than the value of the given node and the child node to its right is greater
than the given node.
Binary Search Tree cannot be used to organize and search through
numeric data, given the complication that arise with very deep trees.
The top node of the binary search tree would be an arbitrary number. All
the nodes to the left of the top node need to be less than the top node’s
number, but they don’t need to ordered in any particular way.
The smallest numeric value would go in the top most node. The next
highest number would go in its left child node, the the next highest number
after that would go in its right child node. This pattern would continue until all
numeric values were in their own node.
Only in some situations, as loops are used only for certain type of
programming.
When you want to run code in one file for a function in another file.
Q57. What is the most self-descriptive way to define a function that calculates
sales tax on a purchase?
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
Q58. What would happen if you did not alter the state of the element that an
algorithm is operating on recursively?
You do not have to alter the state of the element the algorithm is
recursing on.
You would eventually get a KeyError when the recursive portion of the
code ran out of items to recurse on.
explanation
Q59. What is the runtime complexity of searching for an item in a binary search
tree?
The runtime for searching in a binary search tree is O(1) because each
node acts as a key, similar to a dictionary.
The runtime for searching in a binary search tree is O(n!) because every
node must be compared to every other node.
The runtime for searching in a binary search tree is generally O(h), where h
is the height of the tree.
The runtime for searching in a binary search tree is O(n) because every
node in the tree must be visited.
explanation
You use a mixin to make sure that a class’s attributes and methods don’t
interfere with global variables and functions.
If you have many classes that all need to have the same functionality,
you’d use a mixin to define that functionality.
explanation
Q61. What is the runtime complexity of adding an item to a stack and removing
an item from a stack?
Add items to a stack in O(1) time and remove items from a stack on O(n)
time.
Add items to a stack in O(1) time and remove items from a stack in O(1)
time.
Add items to a stack in O(n) time and remove items from a stack on O(1)
time.
Add items to a stack in O(n) time and remove items from a stack on O(n)
time.
Q62. Which statement accurately describes how items are added to and
removed from a stack?
a stacks adds items to one side and removes items from the other side.
a stacks adds items to the top and removes items from the top.
a stacks adds items to the top and removes items from anywhere in the
stack.
a stacks adds items to either end and removes items from either end.
A base case is the condition that allows the algorithm to stop recursing. It
is usually a problem that is small enough to solve directly.
The base case is summary of the overall problem that needs to be solved.
Q64. Why is it considered good practice to open a file from within a Python
script by using the with keyword?
The with keyword lets you choose which application to open the file in.
The with keyword acts like a for loop, and lets you access each line in the
file one by one.
There is no benefit to using the with keyword for opening a file in Python.
When you open a file using the with keyword in Python, Python will make
sure the file gets closed, even if an exception or error is thrown.
explanation
Teams with remote employees use virtual environments so they can share
code, do code reviews, and collaborate remotely.
Q66. What is the correct way to run all the doctests in a given file from the
command line?
python3 <_filename_>
python3 doctest
tutorial video
Q67. What is a lambda function ?
a small, anonymous function that can take any number of arguments but
has only expression to evaluate
Reference
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.
You can access a specific element in a list by indexing to its position, but
you cannot access a specific element in a tuple unless you iterate through the
tuple
Lists are mutable, meaning you can change the data that is inside them at
any time. Tuples are immutable, meaning you cannot change the data that is
inside them once you have created the tuple.
Lists are immutable, meaning you cannot change the data that is inside
them once you have created the list. Tuples are mutable, meaning you can
change the data that is inside them at any time.
Lists can hold several data types inside them at once, but tuples can only
hold the same data type if multiple elements are present.
Static methods can access and modify the state of a class or an instance of
a class.
Static methods are called static because they always return None.
None
An iterable object
Q71. What is the difference between class attributes and instance attributes?
Class attributes are shared by all instances of the class. Instance attributes
may be unique to just that instance
Class attributes belong just to the class, not to instance of that class.
Instance attributes are shared among all instances of a class
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
call.(get_max_num)
-- This is a comment
# This is a comment
/_ This is a comment _\
// This is a comment
Q75. What is the correct syntax for replacing the string 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
Q76. What will happen if you use a while loop and forget to include logic that
eventually causes the while loop to stop?
Nothing will happen; your computer knows when to stop running the
code in the while loop.
A queue adds items to either end and removes items from either end.
A queue adds items to the top and removes items from the top.
A queue adds items to the top, and removes items from anywhere in, a
list.
A queue adds items to the top and removes items from anywhere in the
queue.
Q78. Which choice is the most syntactically correct example of the conditional
branching?
num_people = 5
num_people = 5
num_people = 5
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).
If you try to read from a defaultdict with a nonexistent key, a new default
key-value pair will be created for you instead of throwing a KeyError.
Q80. What is the correct syntax for adding a key called variety to
the fruit_info dictionary that has a value of Red Delicious?
red_delicious = fruit_info['variety']
red_delicious == fruit_info['variety']
when you want to run code in one file while code in another file is also
running
when you want some code to continue running as long as some condition
is true
when you need to run two or more chunks of code at once within the
same file
Simple Example
i = 1
while i<6:
print('Countdown:',i)
i = i + 1
Q82. What is the correct syntax for defining an __init__() method that sets
instance-specific attributes upon creation of a new class instance?
Q83. What would this recursive function print if it is called with no parameters?
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
Q84. In Python, when using sets, you use _ to calculate the intersection between
two sets and _ to calculate the union.
Intersect; union
|; &
&; |
&&; ||
import numpy as np
np.ones([1,2,3,4,5])
It returns a 5x5 matric; each row will have the values 1,2,3,4,5.
Reference
Copy the file to the same directory as where the script is running from
num_list = [21,13,19,3,11,5,18]
num_list.sort()
num_list[len(num_list)//2]
mean
mode
median
average
datetime
dateday
daytime
timedate
Q91. What is the correct syntax for defining a class called Game?
reference here
Q92. What does a class’s init() method do?
The init method makes classes aware of each other if more than one class
is defined in a single code file.
The init method initializes any imports you may have included at the top
of your file.
reference here
Q93. What is the correct syntax for calling an instance method on a class named
Game?
Q94. What is the output of this code? (NumPy has been imported as np.)?
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)
17
4
0
3
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:
num_list = [1,2,3,4,5]
num_list.pop(3)
>>> [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)))
Reference
Q99. Which fragment of code will print exactly the same output as this
fragment?
import math
print(math.pow(2,10)) # prints 2 elevated to the 10th power
print(2^10)
print(2**10)
y = 1
for i in range(1,10):
y = y * 2
print(y)
Reference
Reference
Q101. What is the output of this code? (NumPy has been imported as np.)
table = np.array([
[1,3],
[2,4]])
print(table.max(axis=1))
[2, 4]
[3, 4]
[4]
[1,2]
Reference
Q102. What will this code print?
number = 3
print (f"The number is {number}")
The number is 3
the number is 3
THE NUMBER IS 3
Reference
Reference
Q104. Which mode is not a valid way to access a file from within a Python
script?
write('w')
scan('s')
append('a')
read('r')
Reference
Reference
Q105. Suppose you have a variable named vector of type np.array with 10.000
elements. How can you turn vector into a variable named matrix with
dimensions 100x100?: [ANSWER NEEDED]
matrix = matrix(vector,100,100)
matrix = vector.to_matrix(100,100)
matrix = vector.reshape(100,100)
Example
import numpy as np
vector = np.random.rand(10000)
matrix = a.reshape(100, 100)
print(matrix.shape)
>>> (100, 100)
Q106. NumPy allows you to multiply two arrays without a for loop. This is an
example of _.
vectorization
attributions
accelaration
functional programming
Q107. What built-in Python data type can be used as a hash table?
set
list
tuple
dictionary
Q108. Which Python function allows you to execute Linux shell commands in
Python?
sys.exc_info()
os.system()
os.getcwd()
sys.executable
Q109. Suppose you have the following code snippet and want to extract a list
with only the letters. Which fragment of code will not achieve that goal?
my_dictionary = {
'A': 1,
'B': 2,
'C': 3,
'D': 4,
'E': 5
}
letters = []
letters = my_dictionary.keys()
letters4 = list(my_dictionary)
Explanation: The first one (the correct option) returns the list of the values (the
letters). The rest of the options return a list of the keys.
Q110. When an array is large, NumPy will not print the entire array when given
the built-in 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
You use try/except blocks when you want to run some code, but need a
way to execute different code if an exception is raised.
You use try/except blocks inside of unit tests so that the unit testes will
always pass.
You use 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.
Reference
Q112. In Python, how can the compiler identify the inner block of a for loop?
because of the blank space at the end of the body of the for loop
Q113. What Python mechanism is best suited for telling a user they are using a
deprecated function
sys.stdout
traceback
warnings
exceptions
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.
Q115. If you do not explicitly return a value from a function, what happens?
The function will enter an infinite loop because it will not know when to
stop executing its code.
Q116. How would you access and store all of the keys in this dictionary at once?
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()
Q118. Given that NumPy is imported as 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 *\
Q120. In this code fragment, what will the values of c and d be equivalent to?
import numpy as np
a = np.array([1,2,3])
b = np.array([4,5,6])
c = a*b
d = np.dot(a,b)
A
B
C
d = sum(a) + sum(b)
D
d = sum(c)
Q121. What two functions within the NumPy library could you use to solve a
system of linear equations?
Q122. What is the correct syntax for creating a vaiable that is bound to a list?
Reference
mode
average
mean
median
Explanation: The median is the value separating the higher half from the lower half
of a data sample. Here it is 13.
Q124. What are the two main data structures in the Pandas library?
Reference
Q125. Suppose you have a variale named vector of type np.array with 10,000
elements. How can you turn vector into a variable named matrix with
dimensions 100x100?
matrix = vector.to_matrix(100,100)
matrix = matrix(vector,100,100)
Reference
dictionnary
list
set
string
Reference
myFunction("Spain")
myFunction("")
myFunction()
Q128. Choose the option below for which instance of the class cannot be
created
Anonymous Class
Parent Class
Nested Class
Abstract Class
Reference
Q129. Using Pandas, we load a data set from Kaggle, as structured in the image
below. Which command will return the total number of survivors?
sum(titanic['Survived'])
[x for x in titanic['Survived'] if x == 1]
len(titanic["Survived"])
sum(titanic['Survived']==0)
Q130. How would you create a list of tuples matching these lists of characters
and actors?
list(zip(characters, actors))
d = {}
Q132. Jaccard Similarity is a formula that tells you how similar two sets are. It is
defined as the cardinality of the intersection divided by the cardinality of the
union. Which choice is an accurate implementation in Python?
def jaccard(a, b): return len (a | b) / len (a & b)
Reference
Long
Int
Float
Double
[3,2,3]
[1, 2, 3, 1, 2, 3, 1, 2, 3]
[3,6,9]
Q135. Given a list defined as numbers = [1,2,3,4], what is the value of numbers[-
2]?
1
3
2
Single character strings must be enclosed in single quotes (‘), and the rest
must be enclosed in double quotes (“).