Python Coding Flashcards

1
Q

Can you differentiate between a List and a Tuple?

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

What is __init__() in Python?

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

What is the difference between a mutable data type and an immutable data type?

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

Explain List, Dictionary, and Tuple comprehension

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

What is monkey patching in Python?

A

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

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

What is the Python “with” statement designed for?

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

Why use else in try/except construct in Python?

A

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

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

What are the advantages of NumPy over regular Python lists?

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

What is the difference between merge, join and concatenate?

A

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 well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

How do you identify and deal with missing values?

A

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.

  1. 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.
  2. Fill the missing values with the constant, average, backward fill, and forward fill using the fillna() function. - See note - this can skew the dataset
  3. Replace missing values with a constant String, Integer, or Float using the replace() function.
  4. 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?

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

Define a lambda function, an iterator, and a generator in Python.

A

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 well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

How would you use the ternary operators in Python?

A

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 well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

How do you count the number of islands in a binary matrix?

A
  1. Create a boolean matrix (‘visited’) of the size of the given matrix, enter all data as 0.
  2. Initialize count = 0, to store the answer.
  3. a. Traverse a loop from 0 till ROW
  4. b. Traverse a nested loop from 0 to COL
  5. If the value of the current cell in the given matrix is 1 and is not visited
    Call DFS function
  6. Initialize rowNbr[] = { -1, -1, -1, 0, 0, 1, 1, 1 } and colNbr[] = { -1, 0, 1, -1, 1, -1, 0, 1 } for the neighbour cells.
  7. Mark the current cell as visited (in ‘visited’ matrix)
  8. Run a loop from 0 till 8 to traverse the neighbors
    If the neighbor is safe to visit and is not visited
  9. Call DFS recursively on the neighbor.
    Increment count by 1
  10. Return count as the final answer.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

How would you add two lists together, combining elements in ascending order (not using .sorted!)

A

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
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

Create a solution to identify if a word is a palindrome

A
  1. take each character in input string, enqueue it in a queue, and also push that same character onto a stack.
  2. Interate over range(input_str // 2)
  3. 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)
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

What is a queue vs a stack in Python?

A

These are different ways of adding to lists

Stack: Last in First Out (LIFO)

Queue: First in First Out (FIFO)

17
Q

How can you do a level order traversal of a tree data structure?

A

We need to visit the nodes in a lower level before any node in a higher level, this idea is quite similar to that of a queue.

Push the nodes of a lower level in the queue. When any node is visited, pop that node from the queue and push the child of that node in the queue.

This ensures that the node of a lower level are visited prior to any node of a higher level.

def levelOrder(self,root):
leafs = [root]
while len(leafs) > 0:
leaf = leafs.pop(0)
print(leaf.data, end=” “)
if leaf.left:
leafs.append(leaf.left)
if leaf.right:
leafs.append(leaf.right)

18
Q

What are modules and packages in Python?

A

Modules: Single python files that contains python definitions and statements. Provide a way to organise your code into logical components

Package: Collection of modules organised in a directory structure. Way of grouping modules together to make it easier to manage and distribute code

19
Q

What are global, protected and private attributes?

A

Global: Attributes defined outside of a class and accessible from anywhere. Global Variables are usually capitalised

Protected: Prefaced with an underscore to indicate shouldn’t be used outside of a class, but can be used within subclasses

Private: Prefixed with two underscores. Should not be accessed directly from outside the class. When accessed directly from outside class, the attribute name will be joined with the classname

20
Q

What are Namespaces in Python?

A

Namespaces are containers for attribute names. They are used to prevent conflicts between naming within programs - allowing you to use the same name for different objects in different parts of your code

21
Q

What are decorators in Python?

A

Decorators are a special type of function that modify other functions. This allows you to change functions or classes without editing their code

22
Q

What is Scope Resolution in Python?

A

This is the scope of visibility of different variables, i.e. global visibility or local visibility (only visible inside the class/function where it is defined)

23
Q

What is Pickling in Python?

A

The process of converting a python object hierarchy (list, dict, model) into a bytes stream.

This can then be stored to disk, sent over a network or stored in a database and unpickled to return to original object

24
Q

What are generators in Python?

A

A special type of iterator used to generate values one at a time, instead of generating them all at once as with a list/tuple.

This is more memory efficient

25
Q

How are objects passed around in Python?

A

Objects are passed by reference, meaning that a function receives a reference to an object rather than a copy of the object

This means that any changes to the argument inside a function will affect the original object and will persist outside of the function

An exception to this is numbers and strings which are immutable- here any changes to the object result in a new object being created

26
Q

In Python, how do you access parent class members from a child class?

A

Using super() - this will return a temporary object of the parent class

27
Q

What is inheritance in Python?

A

Inheritance is a key concept in Object Orientated Programming that allows you to create a new class object based on an existing class, inheriting all its properties and behaviours

This reduces duplication and makes maintenance easier

Python also supports multi-inheritance, where a class can be created from more than one base classes

28
Q

What is encapsulation in Python?

A

This is an Object Orientated Programming concept of bundling similar functions and variables together

Python does this through classes methods and attributes

29
Q

In Python, what is data abstraction?

A

Separation of the implementation details of a class from its interface. Only the necessary information is exposed to the outside world