writing · interview prep

The Best Python Interview Preparation Doc

Python for data engineering interviews — 50+ questions, common algorithms from online tests, revision topics, and resources. Give it 2–3 days plus practice.

There are many reasons for choosing python like its Flexible, Easy to Learn, Open Source etc. if not for these definitely consider Python due to its possibilities and ongoing improvement, which will help build amazing products and help businesses.

For Data Engineering python helps you fill in the gaps where normal SQL and Pipeline tools cannot. Moreover, various tools in the market are compatible with Python and allow data engineers to integrate them into their everyday tasks. For other helpful resources on SQL, Python and DSA please head towards: nerdsfornerds.in

Expected time to read: 2 days - 3 days

(excluding practice on Leetcode, HackerRank, other resources shared below)

Some topics to revise before your interview

Here are a few important links for you to go through before you start your preparation:

Preparation from the beginning

Python for all

http://learnpythonthehardway.org/book/

https://realpython.com/start-here/

https://realpython.com/learning-paths/

https://github.com/vinta/awesome-python

https://practice.geeksforgeeks.org/courses/fork-python?vC=1

http://docs.python.org/3/tutorial/index.html

https://calmcode.io/

http://developers.google.com/edu/python

http://codecademy.com/learn/learn-python-3

http://inventwithpython.com/

http://learnpython.org/

http://pythonforbeginners.com/

https://docs.microsoft.com/en-us/learn/paths/beginner-python/

Python for Data Science

https://jakevdp.github.io/PythonDataScienceHandbook/

Python Questions from Top 50 Data Engineer Interview Questions and Answers

location = (28.99, 51.34) We use parenthesis () to declare a tuple.
fruits = ("apple", "banana", "orange") last_fruit = fruits[:-1]

What are lists?

Similar to tuple, lists is another built-in data structure of Python to store data. The syntax to declare a list is:

breakfast = ["bread", "butter", "eggs"]

Similar to tuples , list also supports indexing and slicing

numbers = [1,2,3,4,5]

Which functions and methods can be used on both tuples and lists?

Both the data structures support the following functions:

len(), max(), min(), sum(), any(), all(), sorted()

What are some common methods in list and tuple:

index(), count()
Methods in list: append(), insert(), remove(), pop(), clear(), sort(), and reverse()

What is a ternary operator in Python ?

Ternary operators also known as conditional expressions are operators that evaluate something based on a condition being true or false. It allows testing a condition in a single line replacing the multiline if-else making the code compact

val_return = a if a < b else b
names = ["Alice", "Bob", "Charlie", "David", "Emmanuel", "Fiona"] last        = names[-1] second_last = names[-2] third_last  = names[-3] print(last, second_last, third_last)

List some of the keywords in Python ?

and | def | False | import | not | True
__as__ | __del__ | __finally__ | __in__ | __lambda__ | __try__
__assert__ | __elif__ | __for__ | __is__ | __nonlocal__ | __while__
__break__ | __else__ | __from__ | __None__ | __print__ | __with__
__class__ | __except__ | __global__ | __or__ | __return__ | __yield__
__continue__ | __exec__ | __if__ | __pass__ | __raise__ |

Which are some useful string methods in Python ?

3. Memory Consumption: Python is not a good choice for memory intensive tasks. Due to the flexibility of the data-types, Python's memory consumption is also high.

4. Database Access: Python has limitations with database access . As compared to the popular technologies like JDBC and ODBC, Python's database access layer is found to be a bit underdeveloped and primitive .

5. Runtime Errors: Python programmers cited several issues with the design of the language. Because the language is dynamically typed , it requires more testing and has errors that only show up at runtime .

Life cycle of a thread (https://www.tutorialspoint.com/java/images/Thread_Life_Cycle.jpg

empty_dic = {}

Placing a comma-separated list of key:value pairs within the braces adds initial key:value pairs to the dictionary

student = {'name': "Narendra", 'class': "Junior", 'dob': "2002-01-03"}

Dictionaries are sometimes found in other languages as associative memories or associative arrays.

Unlike sequences, which are indexed by a range of numbers, dictionaries are indexed by keys, which can be any immutable type , strings and numbers can always be keys

Which are the assignment operators in Python ?

def facto(n):
if n==1: return 1 return n*facto(n-1) facto(4)    # This will compute 4x3x2x1 = 24 What does the function zip() do?

- The zip() function returns a zip object, which is an iterator of tuples where the first item in each passed iterator is paired together, and then the second item in each passed iterator is paired together etc.

Syntax: zip(iterator1, iterator2, iterator3 ...) -> zip object

a = ("John", "Charles", "Mike") b = ("Jenny", "Christy", "Monica", "Vicky") x = zip(a, b)

Use the tuple() function to display a readable version of the result:

print(tuple(x)) # prints (('John', 'Jenny'), ('Charles', 'Christy'), ('Mike', 'Monica'))

Given the first and last names of all employees in your firm, what data type will you use to store it?

>>> range(5, 10) range(5, 10) >>> >>> list(range(5, 10)) [5, 6, 7, 8, 9]

When range() is called with a single argument it generates a sequence of numbers from 0 up to the argument specified (but not including it). That's why the number 5 is not included in the sequence.

Here the range() function is called with a step argument of 3, so it will return every third element from 1 to 20 (of course not including 20).

>>> >>> range(1, 20, 3) range(1, 20, 3) >>> >>> >>> list(range(1, 20, 3)) [1, 4, 7, 10, 13, 16, 19] >>>

You can also use the step argument to count backwards. step becomes a negative number in that case

>>> >>> list(range(20, 10, -1)) [20, 19, 18, 17, 16, 15, 14, 13, 12, 11] >>> >>> list(range(20, 10, -5)) [20, 15] >>>

There are two ways to do this:

First: This assigns 3, 4, and 5 to a, b, and c respectively

>>> a,b,c=3,4,5

Second: Ths assigns 3 to a, b, and c

>>> a=b=c=3 # 14. What is the 'with' keyword in Python?
# 15. What is the PYTHONPATH variable?
# 16. Can you do functional programming (FP) in Python ? If yes, then list the commonly used functions to enforce FP in Python.
Function 	| Description
-----------|----------------------------------------------------------
filter() 		|  Filter lets us filter in some values based on conditional logic.
map() 		| Map applies a function to every element in an iterable.
reduce() 	| Reduce repeatedly reduces a sequence pair-wise until we reach a single value. # filter() >>> list(filter(lambda x:x>5,range(8))) # range(8) -> [0,1,2,3,4,5,6,7] # now filter all numbers greater than 5 [6, 7] # map() >>> list(map(lambda x:x**2,range(8))) # range(8) -> [0,1,2,3,4,5,6,7] # now map will apply function x -> x**2 to all numbers from 0 to 7 [0, 1, 4, 9, 16, 25, 36, 49] # reduce() >>> from functools import reduce >>> reduce(lambda x,y:x-y,[1,2,3,4,5]) # step 1 : [-1,3,4,5] # step 2 : [-4,4,5] # step 3 : [-8,5] -13 # 17. Differentiate between the append() and extend() methods of a list.
>>> list1, list2 = [1, 2, 3], [5, 6, 7, 8]
# This is how append() works: >>> list1.append(4) >>> list1 [1, 2, 3, 4]
# And this is how extend() works: >>> list1.extend(list2) >>> list1 [1, 2, 3, 4, 5, 6, 7, 8] # 16. Explain try, raise and finally.
>>> try: print(1/0)
except ValueError: print("This is a value error")
finally: print("This will print no matter what.") # OUTPUT: print("This will print no matter what.") # This will print no matter what.

Because in the try block we got a DivisionByZeroException and not ValueError, so that is not caught and the 'finally' block is executed.

>>> for i,v in enumerate(['Python','C++','Scala']): print(i,v)
# OUTPUT: # 0 Python # 1 C++ # 2 Scala # 18. Evaluate the output of the last line in the following code snippet. >>> A0= dict(zip(('a','b','c','d','e'),(1,2,3,4,5))) >>> A1= range(10) >>> A2= sorted([i for i in A1 if i in A0]) >>> A3= sorted([A0[s] for s in A0]) >>> A4= [i for i in A1 if i in A3] >>> A5= {i:i*i for i in A1} >>> A6= [[i,i*i] for i in A1] >>> A0,A1,A2,A3,A4,A5,A6 # 19. Implement a switch case function using Python. # 20. Write a program in Python to count the number of capital letters in a file. import os dir_path = "C:\Users\1090\" filename = "blob.txt" # change working directory to dir_path os.chdir(dir_path) # open the file
with open(filename) as f: cap_count = 0 # read all characters of the file
for char in f.read():
if char.isupper(): cap_count += 1 print(cap_count) for word in

If you installed a module with pip but it doesn’t import in your IDLE, what could it possibly be?

If while installing a package with pip, you get the error No matching installation found, what can you do?

What is the difference between a Python module and a Python library?

When an object's reference count drops to zero, which means the object is no longer being used, the garbage collector (part of the memory manager) automatically frees the memory from that particular object.

The user need not to worry about memory management as the process of allocation and deallocation of memory is fully automatic. The reclaimed memory can be used by other objects.

A lambda function that adds 10 to the number passed in as an argument, and print the result:

x = lambda a : a + 10 print(x(5)) # prints 15

- Lambda functions can take any number of arguments

A lambda function that multiplies argument a with argument b and print the result:

x = lambda a, b : a * b print(x(5, 6)) # prints 30

- The power of lambda is better shown when you use them as an anonymous function inside another function.

Say you have a function definition that takes one argument, and that argument will be multiplied with an unknown number:

def myfunc(n): return lambda a : a * n

Use that function definition to make a function that always doubles the number you send in

def myfunc(n): return lambda a : a * n mydoubler = myfunc(2) print(mydoubler(11)) # prints 22

Note: Use lambda functions when an anonymous function is required for a short period of time

What are generators in Python ?

What are iterators in Python ?

What is the difference between an iterator and a generator ?

What do you know about palindromes? Can you implement one in Python?

def isPalindrome(string): left, right = 0, len(string)-1
while right >= left:
if not string[left] == string[right]: return False left+=1;right-=1 return True isPalindrome('redrum murder') # returns True isPalindrome('CC.') # returns False __Iterator Implementation:__
def isPalindrome(string): left, right = iter(string), iter(string[::-1]) i=0
while i < len(string)/2:
if next(left) != next(right): return False i+=1 return True isPalindrome('redrum murder') # prints True isPalindrome('CC.') # prints False isPalindrome('CCC.') # prints False isPalindrome('CCC') # prints True
def func(*args):
for i in args: print(i) # call the function func() func(3,2,1,4,7) #output >> 3 2 1 4 7

**kwargs takes keyword arguments when we don’t know how many there will be.

def func(**kwargs):
for i in kwargs: print(i,kwargs[i]) func(a=1,b=2,c=7) >> 	a.1 b.2 c.7
>>> import re >>> rhyme=re.search('.ake','I would make a cake, but I hate to bake') >>> rhyme.group() ‘make’
() is used to specify a group and | stands for __or__
>>> import re
>>> e = re.search(r'[0-9a-zA-Z.]+@[a-zA-Z]+\.(com|co\.in)$', 'abc@gmail.com') >>> e.group() ‘abc@gmail.com’

Important Internet Sources

https://www.techinterviewhandbook.org/best-practice-questions/

https://docs.google.com/spreadsheets/d/1A2PaQKcdwO_lwxz9bAnxXnIQayCouZP6d-ENrBz_NXc/edit#gid=0

https://thedatamonk.com/the-data-monk-booklist/

https://cognitiveclass.ai/courses/python-for-data-science

Asked in Interviews

Solution: Start with two pointers p and q. When the p pointer reaches upto the kth element, increment q.When p reaches the end of the list. q is pointing to the element 'kth' from the end.

List some real world applications of linked lists ?

Solution:

Image viewer – Previous and next images are linked, hence can be accessed by next and previous button.

Previous and next page in web browser – We can access previous and next urls searched in the web browser by pressing back and next button since they are linked as linked lists.

Music Player – Songs in the music player are linked to previous and next songs. you can play songs either from starting or ending of the list.

What is a data structure ?

Solution: Data structure refers to the way data is organized and manipulated. It seeks to find ways to make data access more efficient. When dealing with the data structure, we not only focus on one piece of data but the different set of data and how they can relate to one another in an organized manner.

Explain the LIFO scheme.

Solution: LIFO is a short form of Last In First Out. It refers to how data is accessed, stored and retrieved. Using this scheme, data that was stored last should be the one to be extracted first. This also means that in order to gain access to the first data, all the other data that was stored before this first data must first be retrieved and extracted.

# 7. What is merge sort ?

Solution: Merge sort, is a divide-and-conquer approach for sorting the data. In a sequence of data, adjacent ones are merged and sorted to create bigger sorted lists. These sorted lists are then merged again to form an even bigger sorted list, which continues until you have one single sorted list.

Solution: There are many types of sorting algorithms: quick sort, bubble sort, balloon sort, radix sort, merge sort, etc. Not one can be considered the fastest because each algorithm is designed for a particular data structure and data set. It would depend on the data set that you would want to sort.

Some common algorithm problems asked in online tests :

Save all leaf nodes of a Binary tree in a Doubly Linked List by using Right node as Next node and Left Node as Previous Node.

# Python program to extract leaf nodes from binary tree
# using double linked list
# A binary tree node
class Node:
# Constructor to create a new node
def __init__(self, data): self.data = data self.left = None self.right = None # Main function which extracts all leaves from a given Binary Tree. # The function returns new root of Binary Tree (Note that # root may change if Binary Tree has only one node). # The function also sets *head_ref as head of doubly linked list. # left pointer of tree is used as prev in DLL # and right pointer is used as next
def extractLeafList(root): # Base Case
if root is None: return None if root.left is None and root.right is None: # This node is going to be added to doubly linked # list of leaves, set pointer of this node as # previous head of DLL. We don't need to set left # pointer as left is already None root.right = extractLeafList.head # Change the left pointer of previous head
if extractLeafList.head is not None: extractLeafList.head.left = root # Change head of linked list extractLeafList.head = root return None # Return new root # Recur for right and left subtrees root.right = extractLeafList(root.right) root.left = extractLeafList(root.left) return root # Utility function for printing tree in InOrder
def printInorder(root):
if root is not None: printInorder(root.left) print root.data, printInorder(root.right)
def printList(head):
while(head):
if head.data is not None: print head.data, head = head.right # Driver program to test above function extractLeafList.head = Node(None) root = Node(1) root.left = Node(2) root.right = Node(3) root.left.left = Node(4) root.left.right = Node(5) root.right.right = Node(6) root.left.left.left = Node(7) root.left.left.right = Node(8) root.right.right.left = Node(9) root.right.right.right = Node(10)

print "Inorder traversal of given tree is:"

printInorder(root) root = extractLeafList(root)

print "\nExtract Double Linked List is:"

printList(extractLeafList.head)

print "\nInorder traversal of modified tree is:"

printInorder(root)
# 19. How will you implement a linked list with 1 million nodes? How will you access the 999999th node? Give some optimal design strategy and implementation.
Reversal of Linked List in groups of K.

Given a matrix of characters and a word. You have to count the number of occurrences of that word in that matrix. you can move to any of the eight valid directions from your current position.

Given a binary search tree , print the path which has the sum equal to k and has minimum hops. i.e if there are multiple paths with the sum equal to k then print the path with minimum number of nodes.

A MxN matrix containing integers (positive, negative and zeros). For every position containing 0, mark the corresponding row and column as 0. Rotate MxN matrix by 90 degrees.

Find the nth number that contains the digit k or is divisible by k. (2 <= k <= 9)

Write a program to connect the next left node in a binary tree. Also the first node of each level should be pointing to the last node of the next level? (Without using Queue)

Convert a binary tree to its sum tree(each node is the sum of its children)

Given a directed graph. Construct another graph from a given graph such that if path exists from vertices A to vertices B and from B to C, then path from A to C and from C to A also should exist.

Design a stack which holds an integer value such that getMinimum() function should return the minimum element in the stack. Implement popMin() function which would pop the minimum element from the original stack.

Given a string example : shoppingwithflipkartiseasy. Now we are given this string and a dictionary containing valid words , now we need to break the sentence into words separated by space. Output : shopping with flipkart is easy

Given a series 2,3,4,5,6,8,9,10,……, here in this series all the numbers are present which have factors only and only either 2,3 or 5. Need to write a node to generate the nth number for the series . With best approach and complexity

Given an unsorted array of n integers which can contain integers from 1 to n. Some elements can be repeated multiple times and some other elements can be absent from the array. Count frequency of all elements that are present and print the missing elements.

{1, 0, 1, 0, 1}}
Output : 5

Given two strings in lowercase, the task is to make them anagram. The only allowed operation is to remove a character from any string. Find the minimum number of characters to be deleted to make both the strings anagram?

If two strings contain the same data set in any order then strings are called Anagrams.

Examples:

Examples:

| |
|_|
|    |
|  | |
|__|_|
|   || |
_|_||_||||||
Insert
Remove
Replace

All of the above operations are of equal cost.

Examples:

Examples:

Input: aaabc
Output: abaca
Input: aaabb
Output: ababa
Input: aa
Output: Not Possible
Input: aaaabc
Output: Not Possible

Ending note

Thank you for reading this. If you found this helpful consider posting about these free documents on LinkedIn.

I would love if you will write about it yourself but for the lazy folks like myself, here’s a sample LinkedIn post:

If you post this you are a hero. Thanks for helping me help others.

My complete interview preparation guide — a living document I maintain and update as I learn. If it helped you, drop me a note on LinkedIn.

Keep Hustling! Keep Growing!
say hi! ↴

Prepping for data interviews?

Work through the guide above, then reach out — I answer DMs about breaking into data.