Fatskills
Practice. Master. Repeat.
Study Guide: Useful Python Programs for Interviews
Source: https://www.fatskills.com/python/chapter/useful-python-programs-for-interviews

Useful Python Programs for Interviews

By Fatskills Exam Guides Team — the exam nerds behind 28,500+ quizzes and 2.1M practice questions across 500+ global exams.

⏱️ ~13 min read

1. How can you find the minimum and maximum values present in a tuple?

Solution:
We can use the min() function on top of the tuple to find out the minimum value present in the tuple:
tup1=(1,2,3,4,5)
min(tup1)

Output
1
We see that the minimum value present in the tuple is 1.
Analogous to the min() function is the max() function, which will help us to find out the maximum value present in the tuple:
tup1=(1,2,3,4,5)
max(tup1)

Output
5
We see that the maximum value present in the tuple is 5

2. If you have a list like this -> [1,'a',2,'b',3,'c']. How can you access the 2nd, 4th and 5th elements from this list?
Solution:
We will start off by creating a tuple which will comprise of the indices of elements which we want to access:
Then, we will use a for loop to go through the index values and print them out:
Below is the entire code for the process:
indices = (1,3,4)
for i in indices:
   print(a[i])

3. If you have a list like this -> ['sparta',True,3+4j,False]. How would you reverse the elements of this list?
Solution: 
We can use  the reverse() function on the list:
a.reverse()
a

4. If you have dictionary like this - > fruit={'Apple':10,'Orange':20,'Banana':30,'Guava':40}. How would you update the value of 'Apple' from 10 to 100?
Solution:
This is how you can do it:
fruit["Apple"]=100
fruit
Give in the name of the key inside the parenthesis and assign it a new value.

5. If you have two sets like this -> s1 = {1,2,3,4,5,6}, s2 = {5,6,7,8,9}. How would you find the common elements in these sets.
Solution:
You can use the intersection() function to find the common elements between the two sets:
s1 = {1,2,3,4,5,6}
s2 = {5,6,7,8,9}
s1.intersection(s2)
We see that the common elements between the two sets are 5 & 6.

6. Write a program to print out the 2-table using while loop.
Solution:
Below is the code to print out the 2-table:
Code
i=1
n=2
while i<=10:
   print(n,"*", i, "=", n*i)
   i=i+1

We start off by initializing two variables 'i' and 'n'. 'i' is initialized to 1 and 'n' is initialized to '2'.
Inside the while loop, since the 'i' value goes from 1 to 10, the loop iterates 10 times.
Initially n*i is equal to 2*1, and we print out the value.
Then, 'i' value is incremented and n*i becomes 2*2. We go ahead and print it out.
This process goes on until i value becomes 10.

7. Write a function, which will take in a value and print out if it is even or odd.
Solution:
The below code will do the job:
def even_odd(x):
   if x%2==0:
       print(x," is even")
   else:
       print(x, " is odd")
Here, we start off by creating a method, with the name 'even_odd()'. This function takes a single parameter and prints out if the number taken is even or odd.
Now, let's invoke the function:
even_odd(5)

We see that, when 5 is passed as a parameter into the function, we get the output -> '5 is odd'.

8. Write a python program to print the factorial of a number.
Solution:
Below is the code to print the factorial of a number:
factorial = 1
#check if the number is negative, positive or zero
if num<0:
   print("Sorry, factorial does not exist for negative numbers")
elif num==0:
   print("The factorial of 0 is 1")
else
   for i in range(1,num+1):
       factorial = factorial*i
   print("The factorial of",num,"is",factorial)

We start off by taking an input which is stored in 'num'. Then, we check if 'num' is less than zero and if it is actually less than 0, we print out 'Sorry, factorial does not exist for negative numbers'.
After that, we check,if 'num' is equal to zero, and it that's the case, we print out 'The factorial of 0 is 1'.
On the other hand, if 'num' is greater than 1, we enter the for loop and calculate the factorial of the number.

9. Write a python program to check if the number given is a palindrome or not

Below is the code to Check whether the given number is palindrome or not:
n=int(input("Enter number:"))
temp=n
rev=0
while(n>0)
   dig=n%10
   rev=rev*10+dig
   n=n//10
if(temp==rev):
   print("The number is a palindrome!")
else:
   print("The number isn't a palindrome!")

We will start off by taking an input and store it in 'n' and make a duplicate of it in 'temp'. We will also initialize another variable 'rev' to 0. 
Then, we will enter a while loop which will go on until 'n' becomes 0. 
Inside the loop, we will start off by dividing 'n' with 10 and then store the remainder in 'dig'.
Then, we will multiply 'rev' with 10 and then add 'dig' to it. This result will be stored back in 'rev'.
Going ahead, we will divide 'n' by 10 and store the result back in 'n'
Once the for loop ends, we will compare the values of 'rev' and 'temp'. If they are equal, we will print 'The number is a palindrome', else we will print 'The number isn't a palindrome'.

10. Write a python program to print the following pattern ->
1

2 2

3 3 3

4 4 4 4

5 5 5 5 5

Solution:
Below is the code to print this pattern:
#10 is the total number to print
for num in range(6):
   for i in range(num):
       print(num,end=" ")#print number
   #new line after each row to display pattern correctly
   print("\n")
We are solving the problem with the help of nested for loop. We will have an outer for loop, which goes from 1 to 5. Then, we have an inner for loop, which would print the respective numbers.

11.  Pattern questions. Print the following pattern
#
# #
# # #
# # # #
# # # # #

Solution - >
def pattern_1(num): 
     
   # outer loop handles the number of rows
   # inner loop handles the number of columns 
   # n is the number of rows. 
   for i in range(0, n): 
     # value of j depends on i 
       for j in range(0, i+1): 
         
           # printing hashes
           print("#",end="") 
      
       # ending line after each row 
       print("\r")  
num = int(input("Enter the number of rows in pattern: "))
pattern_1(num)

12. Print the following pattern
 # 
     # # 
   # # # 
 # # # #
# # # # #

Solution:
Code:
def pattern_2(num): 
     
   # define the number of spaces 
   k = 2*num - 2
 
   # outer loop always handles the number of rows 
   # let us use the inner loop to control the number of spaces
   # we need the number of spaces as maximum initially and then decrement it after every iteration
   for i in range(0, num): 
       for j in range(0, k): 
           print(end=" ") 
     
       # decrementing k after each loop 
       k = k - 2
     
       # reinitializing the inner loop to keep a track of the number of columns
       # similar to pattern_1 function
       for j in range(0, i+1):  
           print("# ", end="") 
     
       # ending line after each row 
       print("\r") 
 
num = int(input("Enter the number of rows in pattern: "))
pattern_2(num)

13. Print the following pattern:
0
0 1
0 1 2
0 1 2 3
0 1 2 3 4

Solution:
Code: 
def pattern_3(num): 
     
   # initialising starting number  
   number = 1
   # outer loop always handles the number of rows 
   # let us use the inner loop to control the number 
  
   for i in range(0, num): 
     
       # re assigning number after every iteration
       # ensure the column starts from 0
       number = 0
     
       # inner loop to handle number of columns 
       for j in range(0, i+1): 
         
               # printing number 
           print(number, end=" ") 
         
           # increment number column wise 
           number = number + 1
       # ending line after each row 
       print("\r") 

num = int(input("Enter the number of rows in pattern: "))
pattern_3(num)

14. Print the following pattern:
1
2 3
4 5 6
7 8 9 10
11 12 13 14 15

Solution:
Code: 
def pattern_4(num): 
     
   # initialising starting number  
   number = 1
   # outer loop always handles the number of rows 
   # let us use the inner loop to control the number 
  
   for i in range(0, num): 
     
       # commenting the reinitialization part ensure that numbers are printed continuously
       # ensure the column starts from 0
       number = 0
     
       # inner loop to handle number of columns 
       for j in range(0, i+1): 
         
               # printing number 
           print(number, end=" ") 
         
           # increment number column wise 
           number = number + 1
       # ending line after each row 
       print("\r") 
 
num = int(input("Enter the number of rows in pattern: "))
pattern_4(num)

15. Print the following pattern:
A
B B
C C C
D D D D

Solution:
def pattern_5(num): 
   # initializing value of A as 65
   # ASCII value  equivalent
   number = 65
 
   # outer loop always handles the number of rows 
   for i in range(0, num): 
     
       # inner loop handles the number of columns 
       for j in range(0, i+1): 
         
           # finding the ascii equivalent of the number 
           char = chr(number) 
         
           # printing char value  
           print(char, end=" ") 
     
       # incrementing number 
       number = number + 1
     
       # ending line after each row 
       print("\r") 
 
num = int(input("Enter the number of rows in pattern: "))
pattern_5(num)

16. Print the following pattern:
A
B C
D E F
G H I J
K L M N O
P Q R S T U

Solution:
def  pattern_6(num): 
   # initializing value equivalent to 'A' in ASCII  
   # ASCII value 
   number = 65

   # outer loop always handles the number of rows 
   for i in range(0, num):
       # inner loop to handle number of columns 
       # values changing acc. to outer loop 
       for j in range(0, i+1):
           # explicit conversion of int to char
# returns character equivalent to ASCII. 
           char = chr(number) 
         
           # printing char value  
           print(char, end=" ") 
           # printing the next character by incrementing 
           number = number +1    
       # ending line after each row 
       print("\r") 
num = int(input("enter the number of rows in the pattern: "))
pattern_6(num)

17. Print the following pattern
 #
   # # 
  # # # 
 # # # # 
# # # # #

Solution:
Code: 
def pattern_7(num): 
     
   # number of spaces is a function of the input num 
   k = 2*num - 2
 
   # outer loop always handle the number of rows 
   for i in range(0, num): 
     
       # inner loop used to handle the number of spaces 
       for j in range(0, k): 
           print(end=" ") 
     
       # the variable holding information about number of spaces
       # is decremented after every iteration 
       k = k - 1
     
       # inner loop reinitialized to handle the number of columns  
       for j in range(0, i+1): 
         
           # printing hash
           print("# ", end="") 
     
       # ending line after each row 
       print("\r") 

num = int(input("Enter the number of rows: "))
pattern_7(n)

18. Given the below dataframes form a single dataframe by vertical stacking.
We use the pd.concat and axis as 0 to stack them horizontally.
Code
import pandas as pd
d={"col1":[1,2,3],"col2":['A','B','C']}
df1=pd.DataFrame(d)
d={"col1":[4,5,6],"col2":['D','E','F']}
df2=pd.DataFrame(d)
d_new=pd.comcat([df1,df2],axis=0)
d_new
 

19. Given the below dataframes stack them horizontally to form a single data frame.
We use the pd.concat and axis as 0 to stack them horizontally.
Code
import pandas as pd
d={"col1":[1,2,3],"col2":['A','B','C']}
df1=pd.DataFrame(d)
d={"col1":[4,5,6],"col2":['D','E','F']}
df2=pd.DataFrame(d)
d_new=pd.comcat([df1,df2],axis=1)
d_new
Output

20. If you have a dictionary like this -> d1={'k1″:10,'k2″:20,'k3':30}. How would you increment values of all the keys?
d1={"k1":10,"k2":20,"k3":30}

for i in d1.keys():
 d1[i]=d1[i]+1

21. How can you get a random number in python?
To generate a random, we use a random module of python. Here are some examples To generate a floating-point number from 0-1
import random
n = random.random()
print(n)
To generate a integer between a certain range (say from a to b):
import random
n = random.randint(a,b)
print(n)

 

Also see: All The Useful Python Interview Questions & Answers (For Beginners / Intermediate)

 



ADVERTISEMENT