![]()
Python recursion questions in interview :
Python recursion questions in interview are more often asked to a candidate to check his/her technical expertise. Therefore, in this blog we shall discuss those specific Python questions that uses recursion methodology. Recursion, in short, is type of function that calls it self.
In blog, first we shall look into the basic prototype of a recursion function and then we shall examine few different example of recursive functions.
Basic prototype of any recursive function:
functionName(paramter):
if some condition true/false
terminate the recusion process also called base case
else
take out one unit of paramter + functionName(paramter without the remaining part)
From the psuedo code above, we can infere that there are three main component of a recursive function. Fristly, the base condition, in other words also known as terminating condition. Here the function stops calling itself. Secondly, if the condition is true, the empty unit is returned. example an empty list, empty string or empty node. Thirdly, here we add or attach the a single unit of the parameter with the remaining part of the paramater passed inside the recursive function.
The above explaination may sound blurry but the following examples will make the it clear!
Flatten a nested list using Python recursion :
def recursiveFlatten(nestedList):
resultantList = []
for item in nestedList:
if isinstance(item,list):
resultantList.extend(recursiveFlatten(item))
else:
resultantList.append(item)
return resultantList
dataList = [1,2,3,4,[5,6,[7,8]]]
print(f"after recursively flatenning the given list -->\n{recursiveFlatten(dataList)}")
Recursive sum of a nested list :
def recursiveSum(nestedList):
tempSum = 0
for item in nestedList:
if isinstance(item,list):
tempSum += recursiveSum(item)
else:
tempSum += item
return tempSum
dataList = [1,2,3,4,[5,6,[7,8]]]
print(f"after recursively adding the given list -->\n{recursiveSum(dataList)}")
Reverse list using Python recursion:
def recurListReversal(data):
if len(data) == 0:
return []
else:
return [data[-1]] + recurListReversal(data[:-1])
myDatalist = [1,2,3,4,5,6,7,8,9,10]
print(recurListReversal(myDatalist))
Reverse string using Python recursion:
def recurReverseString(data):
if len(data) == 0:
return data
else:
return data[-1] + recurReverseString(data[:-1])
dataString = "ABCD"
print(f"reversed string -->{recurReverseString(dataString)}")
Prime number check using recursion:
There are two important point to be noted here:
- The isPrime function will work if the value of n is greater than 2.
- As the isPrime function only returns true or false, it can be integrated with filter, lambda and decorator.
def isPrime(n,i=2):
if n == i:
return True
elif n % i == 0:
return False
return isPrime(n, i+1)
dataList = [3,4,5,6,7,8,9,11,13,14]
primeList = list(filter(isPrime,dataList))
print(f"list of prime numbers from dataList -->{primeList}")
Recursive Fibbonacci series :
def recFibonacci(n):
if n <= 1 :
return n
else:
return (recFibonacci(n-1) + recFibonacci(n-2))
resultList = [recFibonacci(i) for i in range(10)]
print(resultList)
Recursively extract key value pairs from nested dictionary:
The nested dictionary below can also be considered as a json data.
def recursive_dict_printer(d):
for key, valueind.items():
if isinstance(value, dict):
recursive_dict_printer(value) # Recursive call
else:
print(f"{key}: {value}")
data = {
'person': {
'name': 'X',
'age': 25,
'contact': {
'email': 'x@gmail.com',
'phone': '879'
}
},
'job': {
'title': 'Cook',
'company': 'Restaurant'
}
}
recursive_dict_printer(data)
Conclusion of Python recursion:
The programs explained above are the few basic recursive functions of Python. These are often asked to check the thinking capacity of an interviewe. However, these programs are merely used in real life scenario. I would request the reader to understand the pattern hidden, so that they could understand the logic behind.
If you wish to learn how to create test cases in Python click here.