Top Python Interview Questions - Solved

Python programming language has become one of the most widely used language with variety of use cases and applications. Here we will explore python interview questions that will help you to understand the types of problem asked in an interview and what could be the solution that we can provide as well as how to answer those. All examples are done with python 3 and above version.

Q: Need to flatten nested list of integer in python.

Lets first understand the example:

Input: listA = [1,2,[3,4,[5,6],7,[7.5]],8]

In the above examples, we have list of numbers both integer and floating numbers (it could also have any type of data) and you can also see that inside list, there are another list having values i.e. we have nested lists here.

In this example there is 3 way nested list but we need to find a generic solution for any typeof nested list.

Required output should be like this : [1, 2, 3, 4, 5, 6, 7, 7.5, 8]
i.e. flattended list

Below is one such solution solved with the help of recursion:

listA = [1,2,[3,4,[5,6],7,[7.5]],8]
res=[]

def nestlistflatten(x):
    if (type(x) is list):
        for i in range(len(x)):
            if (type(x[i]) is list):
                nestlistflatten(x[i])
            else:
                res.append(x[i])
    else:
        res.append(x)

    return(res)

print(nestlistflatten(listA))
		 



Q: Extract integers from a string in python.

Lets first understand the example:

Input String: "There are 142 apples and 23 oranges"

In the above examples, we are given an input string which also contains numbers. Our aim is to fetch only numbers from the string

our required output is : 14223

To solve this interview question we will use regex i.e. regular expression by importing "re"


import re
in_string="There are 142 apples and 23 oranges"
get_numbers=re.sub("\D", "", in_string) #we are replacing characters with blank
print(get_numbers)

	 


Note: The output type will still remain as string until you convert it.

Q: Correct spacing in an input string in python.

Lets first understand the example:

Input String: "incorrect          spacing                  in python"

In the above examples, we are given an input string where we can see that we have unenev spacing which we need to correct.

our required output with correct spacing : incorrect spacing in python

To solve this interview question we will first split the words in that string and then will join with equal spaces.


data="incorrect            spacing                    in python"
out=data.split()
print(" ".join(out))

	 


Note: we have used inbuilt python function i.e. join which is joining words with equal spacing as shown in above example .

Q: How to reverse a string in python.

Lets first understand the example:

Input String: "organize
Outout String: "ezinagro"
This is a simple interview question which we will solve like below.


my_string="organize"

print(my_string[::-1])

	 


Note: we have used inbuilt python functionality of slicing here .

Q: Move zeroes in a list of integers at the end of python list.

Lets first understand the interview problem:

We have given python list random_list: [1,2,0,5,9,23,0,33]

In the above examples, we are given an input list where we have list of integers in an unsorted manner.

our goal in this question it to have list sorted but all zeroes should be at the end of the list :
[1, 2, 5, 9, 23, 33, 0, 0]

To solve this interview question we will first sort and then count zeroes and will move them to end of list.


random_num=[1,2,0,5,9,23,0,33]
random_num.sort()
for i in range(random_num.count(0)):
    random_num.pop(0)
    random_num.append(0)

print(random_num)

	 


Note: we have used inbuilt python function i.e. sort to sort the list . when we used pop(0), in this "0" is the position or index of the list as in the sorted list number 0 is at the 0th index, but in append(0) the 0 will be the element 0 which we are appending.

Q: Given list of integers and find out combination that add up to certain number.

Lets first understand the interview problem:

We have given python list random_list: [2, 3, 6, 7, 9, 12, 15, 4, 5] , target number is 15

In the above examples, we are given an input list where we have list of integers in an certain manner.

our goal in this question it to have all the possible combinations whose sum would result in our target number :
example of one such combination is (6, 4, 5), we have to check all the combinations.

To solve this interview question we will use the inbuilt itertool library.


import itertools

def find_combo(num_list, target):
    results = []
    for r in range(1, len(num_list) + 1):
        combinations = itertools.combinations(num_list, r)
        for combination in combinations:
            if sum(combination) == target:
                results.append(combination)
    return results



num_list = [2, 3,  6, 7, 9, 12, 15, 4, 5]
target = 15

combinations = find_combo(num_list, target)

print(f"Combinations that add up to {target}:")
for combination in combinations:
    print(combination)

	 


Try this in the editor given on this page and understand the code with results.
Below is the snap of executed code:

Q: Write a python program to find anagrams in a sentence provided that word should start with a consonant and no two vowels are together.

Anagram are the words which have same length and same letters.Below is the code written for the given problem. one python library - "itertools" is being used here to check length of word. Fist we will create a function to check if words have same letters.

import itertools

def is_anagram(word1, word2):

    return sorted(word1) == sorted(word2)
		 


Now we will create a function to check if the word starts with a consonant and has no two vowels together

def is_valid_anagram(word):
    vowels = "aeiouAEIOU"
    has_seen_vowel = False
    for letter in word:
        if letter in vowels:
            if has_seen_vowel:
                return False
            has_seen_vowel = True
        else:
has_seen_vowel = False return word[0] not in vowels

Now, we will create our function to find anagrams and will perform below three steps in that function:
Step1 : Split the sentence into words
Step2 : Find all the combinations of words (of length 2) in the sentence
Step3 : Iterate through the combinations and check if they are valid anagrams


def find_anagrams(sentence):
    words = sentence.split()
    word_combinations = itertools.combinations(words, 2)

    anagrams = []
    for combination in word_combinations:
        word1, word2 = combination
        if is_anagram(word1, word2) and is_valid_anagram(word1) and is_valid_anagram(word2):
            anagrams.append(combination)
    return anagrams
	 


Now we will test the function :


sentence = "The cat sat on the back of another cat "
anagrams = find_anagrams(sentence)

print(anagrams)

		 

Q: You are given an array of integers ( with range -10^5 to 10^5) and length of the integer is in range 3 to 1000. We have to return all the triplets which return 0 if added.

Lets first understand the example:

Input: nums = [-1,0,1,2,-1,-4]
Output: [[-1,-1,2],[-1,0,1]]

here we can see that the array is having 6 integers and in the output we have two set of 3 integers from that array whose sum results in 0.



def sum_3(nums):
    nums.sort()
    result = []
    for i in range(len(nums) - 2):
        if i > 0 and nums[i] == nums[i - 1]:
            continue
        l, r = i + 1, len(nums) - 1
        while l < r:
            total = nums[i] + nums[l] + nums[r]
            if total < 0:
               l += 1
            elif total > 0:
               r -= 1
            else:
                result.append([nums[i], nums[l], nums[r]])
                while l < r and nums[l] == nums[l + 1]:
                    l += 1
                while l < r and nums[r] == nums[r - 1]:
                    r -= 1
                    l += 1
                    r -= 1
    return result

# Test the function
print(sum_3([0,0]))
print(sum_3([0,1,1]))

		 


Now, Lets discect the above solution we implemented:
Step1 : Sorts the input array and then iterates through that
Step2 : Hold the first element of the triplet and using two pointers to find the other two elements.
Step3 : If the sum of the three elements is less than 0, then the left pointer will be incremented.
Step4 : If the sum is greater than 0, then the right pointer will be decremented.
Step5 : If the sum is 0, we will add that result set and the pointers will be incremented to the next distinct elements.

In terms of complexity - time complexity : O(n^2) , space complexity : O(1)

Q: Identify number of character to be removed from a string so that it can be presented as a palindrome.

Lets first understand the example:

Input: string1 = "aaasab"
Output: 1

This means that after removing one character, we can represent the string as palindrome.

In the above example, if we remove 's' then the string will become aaaab, which can be written as aabaa - which is a palindrome.

Palindrome is a word which is same when spells backword or forward.

Hence the output is 1. this means we have to remove minimum of one character to make it palindrome enable.



def solutionA(S): 
s1=set(S)
list1=[]
k=0
ans=0
if (S==(S[::-1])):
ans=0
elif (len(S)==2):
ans=1
else:
for a in s1:
list1.append(S.count(a))
for b in list1:
if (int((b/2)) < 1):
list1.pop(b)
else:
k=k+ int((b/2))
if ( (len(S) == (k*2)) or (len(S)== ((k*2)+1)) ):
ans=0
else:
ans=(len(S) - ((k*2)+1))
return ans



print(solutionA("aababaa") )


In case if the given string is already a palindrome, the function should answer 0 i.e. no character to be removed, the string is already in a state where after reposition of characters it can be presented as a palindrome.

Q: Return the smallest positive integer missing from the python list of integers.

Lets first understand the example:

Input: Num_list = [-6,-3,0,1,2,4,5,6]
Output: 3

In the above example, the smallest positive integer missing from the list is 3.

each element of list should be within the range [−1,000,000..1,000,000]


def solution(A):

    for i in range(1, 1000001):

        if i not in A:
            return i
    return 1

print(solution([-1,0,1,3]))

		 


In the above python program, the list will be iterated over the given range of positive integers in ascending order. The first integer which will not be found will be give as output which will also be the smalles integer.

Q: Combine the tuples present within a python list having same initial element.

Lets first understand the example:

Input: [("a", "b"), ("a", "c"), ("b", "d"), ("b", "e"), ("e", "f")]
Output: [('a', 'b', 'c'), ('b', 'd', 'e'), ('e', 'f')]

In the above example, there are tuples inside list. we have to combine tuples which are having same first element.




example_list = [("a", "b"), ("a", "c"), ("b", "d"), ("b", "e"), ("e", "f")]
fin_list = []
t_ele = []
for i in example_list:
	if i[0] not in t_ele:
	    t_ele.append(i[0])

for i in t_ele:
    k = ()
    k=k+(i,)
    for j in example_list:
        if i == j[0]:
            k=k + (j[1],)
    fin_list.append(k)

# printing result
print(fin_list)

 



Q: Check sequence break in a python list of positive integers given what would be the last integer.

Lets first understand the example:

Input: list_is= [1,2,3,4,5,6,7,8,9] , nth integer = 9
Output: "True"

Input: list_is= [1,2,3,4,5,6,7,8,9] , nth integer = 12
Output: "False"

Input: list_is= [1,2,3,4,5,6,8,9] , nth integer = 9
Output: "False"

In the above examples, we have list of positive integers i.e. from 1 and above till given last integer. Also, there should not be any break in the sequence.




def solutiony(A, K):
    n = len(A)
    for i in range(n - 1):
        if (A[i] + 1 < A[i + 1]):
            return False
    if (A[0] != 1 or A[n - 1] != K):
        return False
    else:
        return True

list1=[1,2,3,4,5,6]
print(solutiony(list1,8))

 



Q: Add two binary number given in the form of string and output result in binary.

Let's dive into the interview problem:

We have given two binary numbers in the form of string like below:

a="11" and b="10"

we have to add these numbers and provide the ouput in binary form only which in this case is "101" Thia is a simple interview question asked in many companies.



To solve this interview question we will use format conversion function of python.


a='11'
b='10'

banary_add_out = format((int(a, 2) + int(b, 2)), 'b')

print(banary_add_out)

	 


In the above solution we coverted the binary string into integer and the added the number which then converted into binary to show output.

Try this in the editor given on this page and understand the code with results.
Below is the snap of executed code:

Q: Find out the item within an array or list which has the most number of occurences.

Let's understand the interview problem first:

We have given a list of integers like below:

[1,3,1,3,2,1]

we have to find out the item which is appearing maximum number of times.
This is a simple interview question asked in many companies.



To solve this interview question we will use temporary python dictionary to store the number and number of time it occured in the list or array.


def  most_occur(my_list):
        max_count=0
        max_item='NULL'
        temp_dict={}
        for item in my_list:
                if item not in temp_dict:
                        temp_dict[item] = 1
                else:
                        temp_dict[item]+=1
                if temp_dict[item] > max_count:
                        max_count = temp_dict[item]
                        max_item=item
        return max_item
print(most_occur([1,3,1,3,2,1]))

	 


Try this in the editor given on this site and understand the code with results.
Below is the snap of executed code:

Q: Find out the minimum number of replacements needed so that no three consecutive "a" or"b" should occur .

Let's dive in this interview problem first:

We are given a string having only "a" and "b" like below:

"baaaaa"

In the above string if we replace one "a" with "b" like below then there would be no three consecutive "a" or "b"
"baabaa"
Remember that the replacement letter can be either "a" or "b". Here we do not need to actually replace but we need to find out minimum number of replacements required.
So, for input_string = "baaaaa", function should return 1, as only one replacement is needed.
This type of question is asked in many coding interview questions.



To solve this interview problem we will use slicing of python strings.


def min_replacements(s):

        replace_ab = 0
        i=0

        while i < (len(s)):

                if s[i:i+3] == 'aaa':
                        replace_ab += 1
                        i += 3

                elif s[i:i+3] == 'bbb':
                        replace_ab += 1
                        i += 3
                else :
                        i+=1

        return replace_ab

print(min_replacements("baaabbaabbba"))
print(min_replacements("baaaaa"))
print(min_replacements("baabaa"))

	 


Try this code in the editor given to understand it better.

Try the codes in editor here to understand them better