Different Python Interview Programs
#1. Prime Number Program In Python
This is a frequently asked Python interview program in the technical
round. So let’s check the program with its output.
num = 88
# To take input from the user
# num = int(input("Enter a number: "))
# prime numbers are greater than 1
if num > 1:
# check for factors
for i in range(2, num):
if (num % i) == 0:
print(num, "is not a prime number")
break
else:
print(num, "is a prime number")
#if the input number is less than
or equal to 1,it is not prime
else:
print(num, "is not a prime number")
Output:
88 is not a prime number
#2. Even number using list comprehension in python
For this program, the interviewer may ask you to write this program
using list comprehension. So let’s check the coding for this program.
# list comprehension
even_no = [i for i in range(1,20) if i%2==0]
print(Result:, even_no)
Output:
Result: [2, 4, 6, 8, 10, 12, 14, 16, 18]
#3. Check given number is odd or even in python
num = 89
# To take input from the user
# num = int(input("Enter a number: "))
if (num % 2) == 0:
print(num, "is a even number")
else:
print(num, "is a odd number")
Output:
89 is a odd number
#4. Python dictionary sorting in descending order based on
values
In this type of program, we sort the dictionary in descending order
based on the values declared in the dictionary. This is one of the
Python interview programs that was asked in the technical round.
Method 1:
dict1 = {'Nikhil': {'English': 5, 'Maths': 2, 'Science': 14},
'Akash': {'English': 15, 'Maths': 7, 'Science': 2},
'Akshat': {'English': 5, 'Maths': 50, 'Science': 20}}
def asc(dic):
dict2 = {}
for key, val in dic.items():
dict3 = {}
sort_val = dict(sorted(val.items(), key=lambda item: item[1], reverse=False))
dict3.update(sort_val)
dict2.update({key: dict3})
return dict2
print(asc(dict1))
Output:
{'Nikhil': {'Maths': 2, 'English': 5, 'Science': 14}, 'Akash': {'Science': 2, 'Maths': 7, 'English': 15},
'Akshat': {'English': 5, 'Science': 20, 'Maths': 50}}
Method 2:
import operator
list1 = [[31, 60], [10, 10], [30, 20], [20, 25], [45, 30]]
dict1 = dict(list1)
sort_obj = dict(sorted(dict1.items(), key=operator.itemgetter(1), reverse=False))
mylist = []
for k, v in sort_obj.items():
mylist.append([k,v])
print(mylist)
Output:
[[10, 10], [30, 20], [20, 25], [45, 30], [31, 60]]
Method 3:
print(sorted(list1, key=lambda arg:arg[1]))
Output:
[[10, 10], [30, 20], [20, 25], [45, 30], [31, 60]]
#5. Compare two lists in python and return matches in
python
a = [1, 1, 2, 3, 5, 8, 13, 30, 55]
b = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 10, 13]
print(set(a) & set(b))
Output:
{1, 2, 3, 5, 8, 13}
#6. How to Remove Duplicates From a Python List
mylist = [1, 1, 2, 3, 5, 8, 13, 21, 21, 55, 21]
unique = set(mylist)
print(unique)
Output:
{1, 2, 3, 5, 8, 13, 21, 55}
#7. How to Reverse a List in Python
Method 1: Using Slicing
#Method1: Using Slicing
mylist = [1, 2, 3, 5, 8, 13, 21, 55]
result = mylist[::-1] # using slicing
print(result)
Output:
[55, 21, 13, 8, 5, 3, 2, 1]
Method 2: Using the reverse method
list2 = ['a', 'b', 'c', 'd', 'a', 'a']
list2.reverse()
print (list2)
Output:
['a', 'a', 'd', 'c', 'b', 'a']
#8. How to reverse a string in Python
Method 1: Using slice revers method
string = "abc"
result = string[::-1]
print(result)
Output:
cba
Method 2: Using Python built-in
function reversed & join method
string = "abc"
string = "".join(reversed(string))
print(string)
Output:
cba
Method 3: Using For Loop
def reverse_for_loop(s):
i = ''
for c in s:
i = c + i # appending chars in reverse order
return i
input_str = 'python'
obj = reverse_for_loop(input_str)
print(obj)
Output:
nohtyp
Method 4: Using while loop
def reverse_while_loop(s):
i = ''
length = len(s) - 1
while length >= 0:
i = i + s[length]
length = length - 1
return i
input_str = 'python'
obj = reverse_while_loop(input_str)
print(obj)
Output:
nohtyp
#9. How to make a string palindrome in Python
Method 1:
def isPalindrome(s):
if s.lower() == s[::-1].lower():
print("Yes")
else:
print ("No")
s = "Nitin"
result = isPalindrome(s)
Output
Yes
Method 2:
def isPalindrome(str):
# Run loop from 0 to len/2
for i in range(0, int(len(str) / 2)):
if str[i] != str[len(str) - i - 1]:
return False
return True
# main function
s = "Nitin"
ans = isPalindrome(s)
if (ans):
print("Yes")
else:
print("No")
Output:
No
#10. Find the Second Largest Number in a list in Python
Method 1: Using Python’s built-in sort function
mylist = [12,45,78,60,98,95]
mylist.sort()
print("The Second largest number is:", mylist[-2])
Output:
The Second largest number is: 95
Method 2: Using Python’s built-in method set & remove
mylist = [12,45,78,60,98,95]
new_list = set(mylist)
new_list.remove(max(new_list))
print("The Second Largest number is", max(new_list))
Output:
The Second Largest number is 95
Method 3:
mylist = [1,2,3]
largest = mylist[0]
second_largest = mylist[0]
for i in range(1, len(mylist)):
if mylist[i]> largest:
second_largest=largest
largest=mylist[i]
elif mylist[i]>second_largest:
second_largest=mylist[i]
print("The Second Largest number is", second_largest)
Output:
The Second Largest number is 2
#11. Get repeated item count from list Python
Method 1: Using Python’s collection module.
from collections import Counter
mylist = [1,1,1,8,7,8,1,2,9,2]
result = dict(Counter(mylist))
print(result)
Output:
{1: 4, 8: 2, 7: 1, 2: 2, 9: 1}
Method 2: Using count with dict comprehension and count
method.
result={k:mylist.count(k) for k in mylist}
print (result)
Output:
{1: 4, 8: 2, 7: 1, 2: 2, 9: 1}
#12. Get item index from list Python
mylist = [2,3,1,22,1]
result = [i for i, x in enumerate(mylist) if x == 1]
print(result)
Output:
[2, 4]
#13. How do you swap two variables without using a third
variable in Python?
Method 1:
a = 10
b = 20
print("Before swapping value of a is", a , "and b is", b)
#code to swap a & b
a, b = b, a
print("After swapping value of a is", a , "and b is", b)
Output:
Before swapping value of a is 10 and b is 20
After swapping value of a is 20 and b is 10
Method 2: Using addition & subtraction operators
This method only works for numeric values.
a = 100
b = 202
print("Before swapping value of a is", a , "and b is", b)
#code to swap a & b
a = a + b #30
b = a - b #10
a = a - b #20
print("After swapping value of a is", a , "and b is", b)
Output:
Before swapping value of a is 10 and b is 20
After swapping value of a is 20 and b is 10
Method 3: Using Bitwise XOR operator
a = 10
b = 20
print("Before swapping value of a is", a , "and b is", b)
#code to swap a & b
a=a^b
b=b^a
a=b^a
print("After swapping value of a is", a , "and b is", b)
Output:
Before swapping value of a is 10 and b is 20
After swapping value of a is 20 and b is 10