Different Python Interview Programs
Different Python Interview Programs
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:
# list comprehension
even_no = [i for i in range(1,20) if i%2==0]
print(Result:, even_no)
Output:
Output:
89 is a odd number
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}
Output:
Output:
Output:
Output:
cba
Output:
cba
Output:
nohtyp
Output:
nohtyp
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
Output:
Output:
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:
Output:
{1: 4, 8: 2, 7: 1, 2: 2, 9: 1}
Output:
{1: 4, 8: 2, 7: 1, 2: 2, 9: 1}
Output:
[2, 4]
Output:
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:
Output: