Python Interview Codes

Palindrome:

A palindrome is a word, sentence, verse, or number that reads the same backward or forward. For example: madam, level, noon, etc

Palindrome Code 1: Python program to check if a string is palindrome or not

# Python program to check if a string is palindrome or not

x = input('Enter a number or string:')

# change the string into lower case
x = x.casefold()

# reverse the string
rev_x = reversed(x)

# check if the string is equal to its reverse
if list(x) == list(x):
        print("The string is a palindrome.")
else:
        print("The string is not a palindrome.")

Palindrome Code 2: Using index to reverse the string

#palindrome test using index to reverse it
x = input('Enter a number or string:')
if(x==x[::-1]):
print("The string is a palindrome.")
else:
print("The string is not a palindrome.")

Palindrome Code 3: Using loop

#Using loop
#Enter input string
x = input('Enter a number or string:')

#Declare an empty string variable
rev_x=""

#Iterate string with for loop
for i in x:
rev_x = i+rev_x

if(x==rev_x):

        print("The string is a palindrome.")
else:
        print("The string is not a palindrome.")

Palindrome Code 4: Check whether a number is a palindrome or not

#check if a number is palindrome or not

x = int(input("Enter a number:"))
temp = x
rev = 0
while x > 0:
        digit = x %10
        rev = rev * 10 + digit
        x = x // 10

if(temp == rev):
        print("This number is a palindrome")
else:
        print("This number is not a palindrome")

Armstrong number:

  • If a positive integer is equal to the sum of each digit powered with the total number of digits, then that number is called Armstrong Number.
  • Armstrong numbers are also called narcissist numbers.

 

For example:

153 is an armstrong number because 1 to the power 3 + 5 to the power 3 + 3 to the power 3=153

153, 370, 371,407, 1634 are armstrong numbers

So, a positive integer will be known as an Armstrong number of order n if

abcd… = an + bn + cn + dn + …

Write a program to print whether the given number is an Armstrong number or not.

#take a number input
num = int(input("Enter a number: "))

#initialize a variable to store the sum
numsum = 0

#check the number of digits in the number
n_len = len(str(num))

#store the number in a temporary variable
temp = num

while temp > 0:
        digit = temp % 10
        numsum= numsum+digit ** n_len
        temp //= 10

if num == numsum:
        print(num,"is an Armstrong number")
else:
        print(num,"is not an Armstrong number")

Write a program to print Armstrong numbers in a given range.

#Take number inputs
num1 = int(input("Enter lower range: "))
num2 = int(input("Enter upper range: "))

#loop through the range
for num in range(num1,num2 + 1):
      #variable to store the sum of numbers
numsum = 0
      #store the number of digits in n
n= len(str(num))
    #store the number in temporary variable temp
temp = num

#is the value>0
while temp > 0:
                digit = temp % 10
                numsum= numsum+digit ** n
                temp //= 10

                if num == numsum:
                        print(num)

Fibonacci Series:

The Fibonacci series is a set of integers that starts with a zero, followed by a one, and then follows the rule that each number is equal to the sum of the preceding two numbers.

Example: 0, 1, 1, 2, 3, 5, 8, 13, 21, ….

Program to display the Fibonacci series up to n-th term.

n_terms = int(input("How many terms of fibonacci series you want to print? "))

# declare first two terms
n1=0
n2=1
count = 0

# check if the number of terms is valid or not
if  n_terms <= 0:
        print("Please enter a positive integer")


# if there is only one term, return n1
elif n_terms == 1:
        print("Fibonacci series upto",n_terms,"is")
        print(n1)

# generate fibonacci series
else:
        print("Fibonacci series:")


        while count < n_terms:
        print(n1)
        nth = n1 + n2
        # update values
        n1 = n2
        n2 = nth
        count += 1

List Comprehension

    • List comprehension is creating a list from an existing list.
    • List comprehension is considerably faster than processing a list using the for loop.
    • List comprehension contains three parts:
      • an expression
      • one or more for loop, and
      • one or more if conditions (based on a need).

List Comprehension Program 1:

Create a list of even numbers using List Comprehension

even_num_list = [x for x in range(50) if x%2 == 0]
print(even_num_list)

List Comprehension Program 2:

Print the list of numbers greater than 5 using list comprehension

num_list = [2,4,5,6,7,10,12,15,20]
num_gt_5 = [x for x in num_list if x > 5]

print(num_gt_5)

List Comprehension Program 3:

Print the list of squared numbers if the number in the first list greater than 5.

num_list = [2,4,5,6,7,10,12,15,20]
sqr_num_gt5 = [x*x for x in num_list if x > 5]

print(sqr_num_gt5)

List Comprehension Program 4:

Create a list of results with even or odd in that based on a given list of integers.

my_list = ["Even" if i%2==0 else "Odd" for i in range(10)]
print(my_list)

List Comprehension Program 5:

Create a flat list by using the a list comprising of multiple lists.

One of the applications of list comprehension is to flatten a list comprising of multiple lists, into a single list.

my_list=[[5,10,15],[20,25,30],[35,35,40]]
flat_list=[i for row in my_list for i in row]
print(flat_list)

List Comprehension Program 6:

Create a list by taking all combinations of items from two lists in the form of a tuple and add them in a third list object.

list1 = [5, 3, 9]
list2 = [7, 2, 1]
list3=[(i,j) for i in list1 for j in list2]
print(list3)

List Comprehension Program 7:

From a given numbers list, create a list of numbers that are divisible by 3 but not by 5

my_list = [i for i in range(50) if i%3==0 if i%5!=0]

print(my_list)

List Comprehension Program 8:

Create a list of names that contains ‘m’.

name_list = ['Ram', 'Sam', 'Kris', 'Tom', 'Jim', 'Raj', 'Tina']
name_has_m = [i for i in name_list if 'm' in i]
print(name_has_m)
Python program to reverse a number
n = int(input("Enter a number : "))
print("The number you have entered is:")
reverse = 0
while n!=0:
    reverse = reverse*10 + n%10       
    n = (n//10)
print("Reversed number is:" %reverse) 
Check whether a number is prime or not?
n=int(input("Enter number: "))
temp=0
for i in range(2,n//2+1):
if(n%i==0):
temp=temp+1

if (n==0) or (n==1) or (temp>0):
print(n,'is not prime')
else:
print(n,"is prime")