Wednesday, February 24, 2021

Python programming-oriented interview questions - from Multiple Companies

Python programming-oriented interview questions - from Multiple Companies

=======================================================================

a = 1, 2, 3 "What will be the answer if you print 'a'?
 
Ans: (1, 2, 3) tuple of values

 =========================================================================

Python Interview Questions on Loops 

Given input: "Narendra Boyina"

Required output:

arendra Boyina

Nrendra Boyina

Naendra Boyina

Narndra Boyina

Naredra Boyina

Narenra Boyina

Naendra Boyina

Nrendra Boyina

x = "Narendra Boyina"

y = x.split()  # ["Narendra", "Boyina"]
for in range(len(y[0])):
    y = x.replace(x[i],
"",1)
    
print(y)

==============================================================

"""Find the sum of the series 2 +22 + 222 + 2222 + .. n terms"""

num = int(input("Enter integer value, where you want to stop series : "))
start = 2
sum = 0
for i in range(1, num+1):
print(start, end=" ")
sum += start
start = (start * 10) + 2
print("\nSum of above series is:", sum)

console output:
Enter integer value, where you want to stop series : 4
2 22 222 2222 
Sum of above series is: 2468

==============================================================


"""W.A.P to reverse an integer"""

num = int(input("enter number"))
while num > 0:
    digit = num % 
10    
    
num = num // 10
    
print(digit, end="")
# OR
num = int(input("enter number"))
rev = 
0
while num > 0:
    rev = (rev * 
10) + num % 10
    
num //= 10

print(rev)

==============================================================

""" Python | Permutation of a given string using the inbuilt function"""

from itertools import permutations
s = "Narendra" # check with s="abc" you will get 6 permutations
ps = permutations(s)
count = 0
for i in ps:
print("".join(i))
count += 1
print(count) # 40320 permutations will get for Narendra

==============================================================

""" W.A.P to find the sum of elements in the list"""

list1 = [115171823]
print(sum(list1))

# --->or<---

list_1 = [115171823]

total = 0

for element in list_1:

    total += element  # total = total+i

print(total)

# --->or<---

req = 0
for in range(0len(list1)):
    req =req + list1[i]
print(req)

==============================================================

"""W.A.P to take a list of elements from the user/console """
"""Note:
While giving i/p values via console give with spaces between each value"""

input_string = input("enter list values: ")  # by default, it will consider as string
input_list = input_string.split() # it will give list of strings
print(input_list)

# input via console: enter list values: narendra 55 6.7 mahalakshmi
# output: ['narendra', '55', '6.7', 'mahalakshmi']

"""W.A.P to take a list of numbers from the user/console """

input_string = input("Enter values by providing space b/w each value: ")  
input_list = input_string.split() # it w strings
# below code is for converting each string into integer available in the list
for i in range(len(input_list)):
input_list[i] =
int(input_list[i]) # convert each element to integer type and place in same index
print(input_list)

# input via console:
Enter values by providing space b/w each value: 44 65 23 44
# Output : [44, 65, 23, 44]

=========================================================================

""" W.A.P. to check Armstrong number or not"""

num = int(input("enter a number:"))
sum = 0
temp = num
while temp > 0:
    digit = temp % 10
    sum = sum + digit**3
    temp = temp//10
if num == sum:
    print("given num is Armstrong number")
else:
    print("given number is not Armstrong")

#==================================================================

"" W.A.P to get prime numbers between interval"""

start = int(input("enter"))
end =
int(input("enter"))
for i in range(start, end+1):
   
for j in range(2, i):
       
if i % j == 0:
           
break
    else
:
       
print(i, end=" ")

""" W.A.P to get prime number till given number"""


def prime(num):
   
for i in range(2, num + 1):
       
for j in range(2, i):
           
if i % j == 0:
               
break
        else
:
           
print(i, end=" ")

num = int(input("enter number:"))
prime(num)


===============================================================

""" W.A.P to reverse words in a given string in Python"""

def reverse_string():

    """This function gives reverse of a given string"""

    req_string = string.split()  # converted string to list

    req_string.reverse()

    result = " ".join(req_string)  # joined with none string

    return result

 

string = input("enter string:")

print(reverse_string())

===============================================================

""" W.A.P to print fibonacci series """


 def fibonacci(n):
     n1 = 0
     n2 = 1
     temp = 0
     while temp < n:
         print(temp, end=" ")
         n1 = n2
         n2 = temp
         temp = n1 + n2


 n = int(input(" enter number:"))
 fibonacci(n)

===============================================================

""" W.A.P to find whether a no is the power of two"""


def powerof_2(n):
   
if n == 1:
       
return True
    elif
n % 2 != 0 or n == 0:
        
return False
    return
powerof_2(n / 2)

n =
int(input("enter number"))
print(powerof_2(n))

===============================================================

"""W.A.P to display the only duplicates"""

from collections import Counter

list = [
1,2,3,2,3,4,5,6,7,7]
var =
Counter(list)
print(var)  # Counter({2: 2, 3: 2, 7: 2, 1: 1, 4: 1, 5: 1, 6: 1})
for char,times in var.items():
   
if times>1:
       
print(char,end=" ")

===============================================================

"""W.A.P to print duplicates from a list of integers"""

def duplicate_element():
   
"""This function gives duplicate elements from given list"""
   
repeated = []
   
for i in range(len(list)):
       
for j in range(i+1, len(list)):
           
if list[i] == list[j] and list[i] not in repeated:
                repeated.
append(list[i])
   
return repeated

list = [
1, 3, 3, 2, 4, 4, 5, 6, 6, 8, 7]
print(duplicate_element())

===============================================================

# W.A.P for printing range of float values (Zebra company asked me in 2021)

def test_range(start_val, end_val, step):
    total = start_val
    result =[]
   
while total<end_val:
            total = total+step
            result.
append("{:.2f}".format(total))

   
return result

result =
test_range(0.0, 5.0, 0.2)
print(result)

 =============================================================

A = input (“Enter any number: \t”)            Ex: 7
B = input (“Enter any number: \t”)         Ex: 8
print(A*B)
 

Answer: Error

Reason: input function by default taken as strings

TypeError: can't multiply sequence by non-int of type 'str'

 ============================================================== 

How do you replace a particular value/ string in a list, in multiple places simultaneously?

a= ["Hi",444, "hello",472, "good morning",732, "hello",74.5, "hello", 34]

for i in a:

    if i == "hello":

        a[a.index(i)] = "Narendra"

print(a)

 ============================================================== 

""" W.A.P to replace vowels in a string with a successive alphabet of a vowel

Note: 1 ord() is a Built-in Method that Returns an integer of the Unicode character

Note: 2 chr() is a Built-in Method that Returns a Character (string) from an Integer

vowels_list = ["a""e""i""o""u"]

"""
data = input("Enter any string")
temp = []
for element in data:
if element in vowels_list : # identifying vowels
# converting vowel to ASCII add 1 then converting to string & appending into list
temp.append(chr(ord(
element) + 1))
    else:
temp.append(
element) # placing consonants in a list

required_output = "".join(temp)
print(required_output)

or

 x = input("Enter any string")

print("".join([(chr(ord(elem)+ 1)) if elem in ["a", "e", "i", "o", "u"] else elem for elem  in x]))

 ==============================================================

W.A.P. for converting paragraphs to lines using Python.

= "LOCATE REPO_ENABLE, REPO_DISABLE, PERIODIC, POWER_UP, BATT_WARN, DISCONNECT,

SHUTDOWN, IGNITION_OFF, IGNITION_ON, GEOFENCE_ENTRY, GEOFENCE_EXIT, PARKING,

IDLING, IDLING_END, SPEEDING_END, SPEEDING, GIMPACT_DETECTED"         #paragraph

b=a.split(", ")     # converted into List

for i in b:

print(i)             # lines will be printed.

 =============================================================

 Write a code to sort a numerical list in Python

list = ["2", "7", "4", "3"]
list = [int(i) for i in list] # used list comprehension
list.sort()
print(list)

W. A.P to insert a character at Nth position
def insert_char(user_string, pos, char):
temp = []
for i in user_string:
temp.append(i)
temp.insert(pos, char)
return "".join(temp)


user_string = input("Enter string: ")
pos = int(input("Enter position: "))
char = input("Enter character: ")
print(insert_char(user_string, pos, char))

=========================================================================

""" W.A.P. to Find the missing numbers in the given list. 
Example: input_lst [1, 3, 5, 7] required output : [2, 4, 6, 8]"""

def validate_missing_num(lst):
flag = 0
missed_numbers = []
for n in range(1,11):
if n not in lst:
print(n," is missing")
flag += 1 # flag to count no of missing numbers
missed_numbers.append(n)
else:
continue
if flag == 0: # when flag is 0 print "no missing numbers"
print("Nothing is missing")
else:
print("missed numbers are :{}".format(missed_numbers))



input_lst = [1, 2, 4, 5, 8, 10]
validate_missing_num(input_lst)

=========================================================================

""" W.A.P to validate whether the given string is in the correct consecutive alphabet order or not?"""


def consecutive_str_validate(input_string):

    l = len(input_string)

    s = ''.join(sorted(input_string))

    for i in range(1, l):

        if ord(s[i]) - ord(s[i - 1]) != 1:

            return False

    return True


if _name_ == "_main_":

    input_string = "bcd"

    if consecutive_str_validate(input_string):

        print("true")

    else:

        print("false")

    input_string = "ghj"

    if consecutive_str_validate(input_string):

        print("true")

    else:

        print("false")

======================================================================

""" Write a Python function that accepts a string and

calculate the number of upper case letters and lower case letters."""

def test_str(str):
    d = {
'uppercase'0'lowercase'0}
    
for in str:
        
if i.isupper():
            d[
'uppercase'] += 1
        
elif i.islower():
            d[
'lowercase'] += 1
    
else:
        
pass
    print
("upper case count {0}\nlower count {1}".format(d['uppercase'], d['lowercase']))


str = 
input("enter a string: ")
test_str(str)

===================================================================

""" Write a Python function that takes a list and returns a new list with unique elements of the first list."""

def unique_list(data):
    req = []
    for element  in data:
        if element not in req:
            req.append(element)
 
    print(req)


data = [
5, 3, 1,3, 4, 5, 6, 6, 68, 8, 8, 8, 68]
unique_list(data)

==================================================================


Python Interview Questions on Recursive Functions 

W.A.P. to calculate the sum of a list of numbers or Recursive function example.


def sum(num):
if len(num) == 1:
# if only one element in the list, sum result will be equal to the element
return num[0]
else:
return num[0] + sum(num[1:])

print(sum([2, 5, 3, 6, 4]))

 ==========================================================


Python Interview Questions on Functions 

""" Write a Python function to sum all the numbers in a list"""
def 
addition(numbers):
    total = 0
    for i in numbers:
        total +=i
    
return total
numbers = [
3,5,2,7,5,8,8]
total = addition(numbers)

print(total)

=====================================================

""" Write a Python function to multiply all the numbers in a list"""
def multiply(numbers):
    mul = 
1
    
for num in numbers:
        mul *= num   # mul = mul*
    
print(mul)


multiply([435, -2])    # calling function
#==============================================================


""" Write a Python function to calculate the factorial of a number"""
def factorial(n):
    
if n == 0:
        
print("1")
    
else:
        fac = 
1
        
for in range(1, n+1):
            fac *= i  # fac = fac*i
        
print("factorial of", n, "is", fac)

n = 
int(input("enter a number :"))
factorial(n)

# --->or<---

import math
print(math.factorial(5))

# =====================================================

What is An anagram? Explain with an example

An anagram is the result of rearranging the letters of a word or phrase to produce a new word or phrase,

using all the original letters exactly once;

for example, the word cautioned can be rearranged into education.

 def is_anagram (str1, str2):

    list_str1 = list(str1)
list_str1.sort()
list_str2 = list(str2)
list_str2.sort()
return (list_str1 == list_str2)

print(is_anagram("cautioned", "education"))
print(is_anagram("cat", "rat"))

                    Or

def anagram(str1, str2):
if sorted(str1) == sorted(str2):
print("given strings are anagram")
else:
print("given strings are not anagram")


anagram("cautioned", "education") # given strings are anagram
anagram("anagram", "annagaram") # given strings are not anagram

================================================================

""" insert a character at nth position"""
def ins_char():
    user_string =
input("enter string")
    pos =
int(input("enter position"))
    char =
input("enter character")
    l = []
   
for i in user_string:
        l.
append(i)
    l.
insert(pos, char)
   
print("".join(l))


ins_char()

 ================================================================

""" Sorting dictionaries based on value"""
a = {1:23,2:1,3:11}
print(sorted(a.items(), key lambda x:x[1])) # [(2, 1), (3, 11), (1, 23)] list of tuples
print(dict(sorted(a.items(), key lambda x:x[1]))) # converted into dictionary {2: 1, 3: 11, 1: 23}

==============================================================

""" Sorting list of lists based on the second element in each list"""
# Given input Ã¨ [[1,3,5], [3,4,6], [1,2,3]]
# Required output 
è [[1, 2, 3], [1, 3, 5], [3, 4, 6]]
list_a=[[1,3,5], [3,4,6], [1,2,3]]
a = 
sorted(list_a,key lambda x : x[1])
print(a) #[[1, 2, 3], [1, 3, 5], [3, 4, 6]]

==============================================================

import random

l = [
12"sree"103"kanth"4567]
x = random.
sample(l, 1)
l.
remove(x[0])  # x gives the list of number of sample values
print(x[0], " is removed from the list")
print(l)


"""--- using the pop function"""

l = [12"sree"103"kanth"4567]
print(l.pop(l.index(random.sample(l, 1)[0])))
print(x, l)

==============================================================

What will be the output for the following code 

def Narendra(x,*y,**z):
   
print(x)
   
print(*y)
   
print(**z)
Narendra(
152345"Bhagyasree"=11y=12z=13)

==============================================================

# Python program to check the validation of the password

password as a combination of alphanumeric characters along with special characters, and check whether the password is valid or not with the help of f bew conditions.

Primary conditions for password validation :

1. Minimum 8 characters.

2. The alphabet must be between [a - z]

3. At least one alphabet should be in Upper Case [A-Z]

4. At least 1 number or digit between [0-9].

5. At least 1 character from [ _ or @ or $ ].

# Module of a regular expression is used with search()

 import re


password = "R@m@_f0rtu9e$"
flag = 0
while True:
if (len(password) < 8):
flag = -1
break
elif not re.search("[a-z]", password):
flag = -1
break
elif not re.search("[A-Z]", password):
flag = -1
break
elif not re.search("[0-9]", password):
flag = -1
break
elif not re.search("[_@$]", password):
flag = -1
break
elif re.search("\s", password):
flag = -1
break
else:
flag = 0
print("Valid Password")
break
if flag == -1:
print("Not a Valid Password")

========================================================================

def get_packet_list(cmd):

        '''

        returns Packet List. Used by other Keywords internally

        INPUT: `cmd`` :- Tshark command to be executed

        OUTPUT: Returns Packets as List of Dictionaries on success

        Usage:         Packet_list=get_packet_list(cmd)

        '''

        print(cmd)

        fh=os.popen(cmd)

        data_dict=dict()

        data_dict_list=[]

        index=0

        for eachLine in fh.readlines():

               eachLine = eachLine[:-1]   

               if index == 0:

                       headers = eachLine.split('|')

               else:

                       data_list = eachLine.split('|')

                       data_dict = dict(zip(headers, data_list))  

                       data_dict_list.append(data_dict)

               index +=1

        return data_dict_list

def tx_packets_count_per_second_from_source(pcap_file_path, source_ip_address):

     cmd = 'tshark -r {pcap_file_path} -E header=y -Y "(ip.src=={source_ip_address} and udp)" -E separator="|" -T fields -e frame.number -e frame.time_epoch'.format(pcap_file_path= pcap_file_path, source_ip_address= source_ip_address)

        print("Command to be executed : {cmd} ".format(cmd=cmd))

        response = get_packet_list(cmd)

        l = [i['frame.time_epoch'].split(".")[0] for i in response]

        dict_pkts = {time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(float(i))):l.count(i) for i in l}

        df = pd.DataFrame(data=dict_pkts, index=["Tx_Pkts_count"])

        df = (df.T)

        df.to_excel("Tx_packets.xlsx",sheet_name="UDP_Tx_packets",index_label="Seconds")

 

 

Calling function:

==============

if __name__ == '__main__':

    pcap_file_path = r"C:\Narendra\23feb2022\-pktcap-2022-01-11_13.54.27.pcap"

    source_ip_address = "192.168.xx.xxx"

    tx_packets_count_per_second_from_source(pcap_file_path, source_ip_address)

 

output:

======

In Excel sheet you will get the number of UDP packets transmitted per second.

Example:

========

Seconds     Tx_Pkts_count

2022-01-11 13:54:45  8

2022-01-11 13:54:46  2

2022-01-11 13:54:47  2

2022-01-11 13:54:48  2

2022-01-11 13:54:49  2

2022-01-11 13:54:50  2

2022-01-11 13:54:51  2

2022-01-11 13:54:52  2

2022-01-11 13:54:53  2

2022-01-11 13:54:54  2

2022-01-11 13:54:55  2

2022-01-11 13:54:56  33

2022-01-11 13:54:57  51

2022-01-11 13:54:58  53

2022-01-11 13:54:59  52

==============================================================

def terminate_thread(cmd_pipe,  timeout):

         st_time = time.time()

         while not teminate_flag():

                 if (time.time() - st_time) > timeout:

                          try:

                                   cmd_pipe.terminate()

                          except:

                                   pass

                          break

 

 

def teminate_flag(value=-1):

         global terminate_flg

         if value < 0:

                 return terminate_flg

         else:

                 terminate_flg = value

 

def run_adb_command(cmd, adb_timeout = 300):

         """

         Runs ADB command and returns its output as a list of lines

         This method uses subprocess.Popen to run the command

         It waits for 300 secs for the command to get completed

         Commands like "adb shell" is not supported as this is blocked

         until user gives input. Do not use this method for adb commands which

         gives huge output data (for example 1 Kb of data)

         :param cmd: Command to be executed

         :return: list of lines

         """

         output = ''

         error = ''

         log_message("ADB_CMD", "{cmd}".format(cmd=cmd))

         cmd_pipe = subprocess.Popen(cmd, stdout=subprocess.PIPE,stderr=subprocess.PIPE)

         st_time = time.time()

         teminate_flag(0)

         thr = threading.Thread(target=terminate_thread, args=(cmd_pipe, adb_timeout))

         thr.start()

 

         while cmd_pipe.poll() is None:

                 output += cmd_pipe.stdout.readline()

 

                 if (time.time() - st_time) > adb_timeout:

                          break

 

         teminate_flag(1)

         thr.join()

         print "Command run for {time:0.2f} secs".format(time = (time.time() - st_time) )

         try:

                 cmd_pipe.terminate()

         except:

                 pass

         (out, err) = cmd_pipe.communicate()

         output += out

         error += err

         if error:

                 print("run_adb_command:  Error {error} while running command ".format(error=error)

         return re.split(b"\n+", output))


===========================================================

import os

import glob

os.chdir(r"path of  directory")

file = glob.glob(".txt")

print(file)

 =============================================================

Python Interview Questions on Files & Folders(directories) 


 """ W.A.P to count the number of lines in a text file """

file = open("Narendra.txt", "r")

print("Number of lines:", len(file.read().split("\n")))

### OR ###

print("Number of lines:", len(open("Narendra.txt", "r").readlines()))

=========================================================================

 """ W.A.P to get only .txt/.json/.py/.xml/.xls files in the directory """

import os

def get_file_names_based_on_extension(path, extension):

    for root, dirs, files in os.walk(path):

        for file in files:

            if file.endswith(extension):

                print(file)

 

path = r"E:\Narendra_Training_Data\Automation_Training_Data\Narendra_python_Feb2021"

extension =".py"

get_file_names_based_on_extension(path,extension)

==============================================================

"""Create 15 folders & each folder should contain one text file"""

import os

name = input("Enter any name : ")

for in range(115):

x = name+"_"+str(i) # creating directory name

os.mkdir(x) # creating folder

os.chdir(x) # entering in to that directory

y = x+".txt" # creating file name

open(y,"a+"# creating a file

os.chdir(path)

x = y = ""

=============================================================

""W.A.P to cretae 15 directories, each directory should contain one sub directory,
and that sub directory should contain one file with data"""


import os


def create_multi_lvl_dir_file(d_name, sub_d_name, f_name):
"""
Based on the input names provided by the used this function will create multi level directories
Also this function will create a file inside it along with some content
:param d_name: main directory name
:param sub_d_name: sub directory name
:param f_name: file name
:return: None
"""
root_path = os.getcwd()
for i in range(1, 16):
dir_name = d_name+"_"+str(i) # preparing directory name
os.mkdir(dir_name) # creating directory
os.chdir(dir_name) # moving into the directory
subdir_name = sub_d_name+"_"+str(i) # preparing sub directory name
os.makedirs(subdir_name) # creating sub directory
os.chdir(subdir_name) # moving into the sub directory
file_name = f_name+"_"+str(i)+".txt" # preparing file name
with open(file_name, "w+") as f_obj: # creating file
f_obj.write("This file created inside subdirectory") # writing content to the file
os.chdir(root_path)


d_name = input("Enter required directory name: ") # Narendra
sub_d_name = input("Enter required subdirectory name: ") # Mahalakshmi
f_name = input("Enter required file name: ") # Raj
create_multi_lvl_dir_file(d_name, sub_d_name, f_name) # calling function

=============================================================

"""W. A.P to create 20 directories, each directory should contain one text file & one directory, 
and each inner directory should have a file in it.

Note:The file names should be different in directories and content should be different in those files"""

def create_multi_lvl_dir_file(d_name, sub_d_name, f_name):
"""
:param d_name: main directory name
:param sub_d_name: sub directory name
:param f_name: file name
:return: None
"""
root_path = os.getcwd()
for i in range(1, 21):
dir_name = d_name+"_"+str(i) # preparing directory name
os.mkdir(dir_name) # creating directory
os.chdir(dir_name) # moving into the directory
subdir_name = sub_d_name+"_"+str(i) # preparing sub directory name
os.makedirs(subdir_name) # creating sub directory
file_name_fr_main_dir = subdir_name+".txt" # preparing file name
with open(file_name_fr_main_dir, "w+") as f_obj: # creating file in main directory
f_obj.write("This file created in main subdirectory") # writing content to the file
os.chdir(subdir_name) # moving into the sub directory
file_name = f_name+"_"+str(i)+".txt" # preparing file name
with open(file_name, "w+") as f_obj: # creating file
f_obj.write("This file created inside subdirectory") # writing content to the file
os.chdir(root_path)


d_name = input("Enter required directory name: ") # Narendra
sub_d_name = input("Enter required subdirectory name: ") # Mahalakshmi
f_name = input("Enter required file name: ") # Raj

create_multi_lvl_dir_file(d_name, sub_d_name, f_name) # calling function=



RequestIf you find this information useful, please provide your valuable comments.