Python Coding Flashcards
Can you differentiate between a List and a Tuple?
List
- Mutable data type, consumes more memory, better for element insertion and deletion. Furthermore, it has several building functions, and the implication of iterations is slower compared to Tuple.
Tuple
The Tuple is an immutable data type, and it is generally used for accessing the elements. It is faster and consumes less memory, but it lacks built-in methods.
What is __init__() in Python?
It is known as a constructor in OOP terminology. It is used to initiate a state when you create a new object. For example, you can assign values to object properties or run the operations that are necessary when the object is created.
The __init__() method is reserved for Python classes, and it is called automatically when you create a new object.
What is the difference between a mutable data type and an immutable data type?
The mutable Python data types can be modified, and they can change at runtime, for example, a List, Dictionary, and Set.
The immutable Python data types can not be changed or modified, and they remain unchanged during runtime, for example, a Numeric, String, and Tuple.
Explain List, Dictionary, and Tuple comprehension
List/dict comprehension offer one-liner syntax to create a new list/dict based on the values of an existing list. You can use a for loop
to replicate the same thing, but it will require you to write multiple lines, and sometimes it can get complex.
Tuple comprehension returns a generator object, not a tuple comprehension.
What is monkey patching in Python?
Monkey patching in Python is a dynamic technique that can change the behavior of the code at run-time. In short, you can modify a class or module at run-time.
class monkey:
def patch(self):
print (“patch() is being called”)
def monk_p(self):
print (“monk_p() is being called”)
replacing address of “patch” with “monk_p”
monkey.patch = monk_p
obj = monkey()
obj.patch()
# monk_p() is being called
What is the Python “with” statement designed for?
The with
statement is used for exception handling to make code cleaner and simpler. It is generally used for the management of common resources like creating, editing, and saving a file.
Why use else in try/except construct in Python?
try:
and except:
are commonly known for exceptional handling in Python, so where does else:
come in handy? else:
will be triggered when no exception is raised.
try:
x
except:
y
else:
z
What are the advantages of NumPy over regular Python lists?
Memory
Numpy arrays consume less memory.
For example, if you create a list and a Numpy array of a thousand elements. The list will consume 48K bytes, and the Numpy array will consume 8k bytes of memory.
Speed
Numpy arrays take less time to perform the operations on arrays than lists.
For example, if we are multiplying two lists and two Numpy arrays of 1 million elements together. It took 0.15 seconds for the list and 0.0059 seconds for the array to operate.
Vesititly
Numpy arrays are convenient to use as they offer simple array multiple, addition, and a lot more built-in functionality. Whereas Python lists are incapable of running basic operations.
What is the difference between merge, join and concatenate?
join(): it combines two DataFrames by index.
merge(): it combines two DataFrames by the column or columns you specify.
concat(): it combines two or more DataFrames vertically or horizontally.
How do you identify and deal with missing values?
We can identify missing values in the DataFrame by using the isnull()
function and then applying sum()
. Isnull()
will return boolean values, and the sum will give you the number of missing values in each column.
There are various ways of dealing with missing values.
- Drop the entire row or the columns if it consists of missing values using
dropna()
. This method is not recommended, as you will lose important information. - Fill the missing values with the constant, average, backward fill, and forward fill using the
fillna()
function. - See note - this can skew the dataset - Replace missing values with a constant String, Integer, or Float using the
replace()
function. - Fill in the missing values using an interpolation method. - See note - this can skew the dataset
Note, stratification is needed to explore missing data - why is data missing, is one demographic affected more than another, is missing data interesting in itself?
Define a lambda function, an iterator, and a generator in Python.
Lambda function: also known as an anonymous function. You can add any number of parameters but with only one statement.
Iterator: an object that we can use to iterate over iterable objects like lists, dictionaries, tuples, and sets.
Generator: function similar to a normal function, but it generates a value using the yield keyword instead of return. If the function body contains yield, it automatically becomes a generator.
How would you use the ternary operators in Python?
Ternary operators are also known as conditional expressions. They are operators that evaluate expression based on conditions being True and False.
You can write conditional expressions in a single line instead of writing using multiple lines of if-else statements. It allows you to write clean and compact code.
How do you count the number of islands in a binary matrix?
- Create a boolean matrix (‘visited’) of the size of the given matrix, enter all data as 0.
- Initialize count = 0, to store the answer.
- a. Traverse a loop from 0 till ROW
- b. Traverse a nested loop from 0 to COL
- If the value of the current cell in the given matrix is 1 and is not visited
Call DFS function - Initialize rowNbr[] = { -1, -1, -1, 0, 0, 1, 1, 1 } and colNbr[] = { -1, 0, 1, -1, 1, -1, 0, 1 } for the neighbour cells.
- Mark the current cell as visited (in ‘visited’ matrix)
- Run a loop from 0 till 8 to traverse the neighbors
If the neighbor is safe to visit and is not visited - Call DFS recursively on the neighbor.
Increment count by 1 - Return count as the final answer.
How would you add two lists together, combining elements in ascending order (not using .sorted!)
Create a new linked list and initialize a zero pointer that points to the first node. Then iterate using the pointer continuously adding nodes in the linked list while traversing both lists.
class Solution:
def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode:
head = l3 = ListNode(0)
while True: if l1 is None and l2 is None: break elif l1 is None: l3.next = l2 break elif l2 is None: l3.next = l1 break else: smallvalue = 0 if l1.val < l2.val: smallvalue = l1.val l1 = l1.next else: smallvalue = l2.val l2 = l2.next new_node = ListNode(smallvalue) l3.next = new_node l3 = l3.next return head.next
Create a solution to identify if a word is a palindrome
- take each character in input string, enqueue it in a queue, and also push that same character onto a stack.
- Interate over range(input_str // 2)
- dequeue the first character from the queue and pop the top character off the stack, then compare the two characters to see if they are the same; as long as the characters match, we continue dequeueing, popping, and comparing each character until our containers are empty (a non-match means isn’t a palindrome - can break loop)
class Solution:
def __init__(self):
self.stack = []
self.queue = []
def pushCharacter(self, char): self.stack.insert(0, char) def enqueueCharacter(self, char): self.queue.append(char) def popCharacter(self): return self.stack.pop(0) def dequeueCharacter(self): return self.queue.pop(0)