Search This Blog

Wednesday, February 10, 2021

Python programs with solution - Interview

How to Reverse a String in Python
Python string library doesn’t support the in-built “reverse()” as done by other python containers like list, hence knowing other methods to reverse string can prove to be useful

1) Using loop
def reverse(s):
  str = ""
  for i in s:
    str = i + str
  return str
  
s = "OkGuru"
  
print ("The original string  is : ",end="")
print (s)
  
print ("The reversed string(using loops) is : ",end="")
print (reverse(s))

Output:
The original string  is : OkGuru
The reversed string(using loops) is : uruGkO


2) Using recursion

def reverse(s):
    if len(s) == 0:
        return s
    else:
        return reverse(s[1:]) + s[0]
  
s = "OkGuru"
  
print ("The original string  is : ",end="")
print (s)
  
print ("The reversed string(using recursion) is : ",end="")
print (reverse(s))

Output
The original string  is : OkGuru
The reversed string(using recursion) is : uruGkO

3) Using extended slice syntax
# Function to reverse a string
def reverse(string):
   string = string[::-1]
   
s = "OkGuru"
print ("The original string  is : ",end="")
print (s)
print ("The reversed string(using extended slice syntax) is : ",end="")
print (reverse(s))

Output:
The original string is : OkGuru
The reversed string(using extended slice syntax) is :uruGkO
4) Using reversed
# Function to reverse a string
def reverse(string):
  string = "".join(reversed(string))
  return string
  
s = "OkGuru"
  
print ("The original string  is : ",end="")
print (s)
  
print ("The reversed string(using reversed) is : ",end="")
print (reverse(s))

Output
The original string  is : OkGuru
The reversed string(using reversed) is : uruGkO

Return maximum occurring character in an input string

Method 1
# Python program to return the maximum occurring character in the input string
ASCII_SIZE = 256
 
def getMaxOccuringChar(str):
    # Create array to keep the count of individual characters
    # Initialize the count array to zero
    count = [0] * ASCII_SIZE
 
    # Utility variables
    max = -1
    c = ''
 
    # Traversing through the string and maintaining the count of
    # each character
    for i in str:
        count[ord(i)]+=1;
 
    for i in str:
        if max < count[ord(i)]:
            max = count[ord(i)]
            c = i
 
    return c

# Driver program to test the above function
str = "sample string"
print "Max occurring character is " + getMaxOccuringChar(str)

Method2
# Shorter version of the program
import collections
str = "sample string"
print "Max occurring character is " +
       collections.Counter(str).most_common(1)[0][0]

Program to check if characters of a given string can be rearranged to form a palindrome
Algorithm:
We can do it in O(n) time using a count array. Following are detailed steps. 
  1. Create a count array of alphabet size which is typically 256. Initialize all values of count array as 0.
  2. Traverse the given string and increment count of every character.
  3. Traverse the count array and if the count array has more than one odd values, return false. Otherwise, return true.
NO_OF_CHARS = 256
 
# function to check whether characters
# of a string can form a palindrome
  
def canFormPalindrome(st):
# Create a count array and initialize
    # all values as 0
    count = [0] * (NO_OF_CHARS)
 
    # For each character in input strings,
    # increment count in the corresponding
    # count array
    for i in range(0, len(st)):
        count[ord(st[i])] = count[ord(st[i])] + 1
 
    # Count odd occurring characters
    odd = 0
 
    for i in range(0, NO_OF_CHARS):
        if (count[i] & 1):
            odd = odd + 1

if (odd > 1):
            return False
 
    # Return true if odd count is 0 or 1,
    return True

# Driver code
if(canFormPalindrome("test")):
    print("Yes")
else:
    print("No")
 
if(canFormPalindrome("saas")):
    print("Yes")
else:
    print("No")

Output
No
Yes
Write a python function to send email notification.
Input: Receiver email address, subject line , message body


 Write a function to save python dictionary to file which takes dict and file as input
Also write another function to load the saved dictionary into python and load function must take  file to the saved dictionary as the input and return the dictionary object


How to search for a pattern in log file


Find maximum consecutive repeating character in string

Input : str = "seeekk"
Output : e

Input : str = "aaaabbcbbb"
Output : a

The idea is to reset the count as 1 as soon as we find a character not matching with previous.





Dictionary Attack using Python

Suppose you were scanning for a 3-way handshake between an FTP server and a client and you were successful in doing so too. But as you guys might already know, passwords are never really stored in plain text. They are always hashed before being stored in a database and normally the hash itself is compared for verification purposes. Let us create a small Python program that can be used to crack a password using the dictionary attack method.

import hashlib
 
flag = 0
 
pass_hash = input("md5 hash: ")
 
wordlist = input("File name: ")
try:
    pass_file = open(wordlist,"r")
except:
    print("No file found :(")
    quit()
 
for word in pass_file:
 
    enc_wrd =word.encode('utf-8')
    digest =hashlib.md5(enc_wrd.strip()).hexdigest()
    # print(word)
    # print(digest)
    # print(pass_hash)

    if digest.strip() == pass_hash.strip():
        print("password found")
        print("Password is " + word)
        flag = 1
        break
 
if flag == 0:
    print("password not in list")


Write a program to find most frequent element in an array

Examples: 

Input : arr[] = {1, 3, 2, 1, 4, 1}
Output : 1
1 appears three times in array which
is maximum frequency.

Input : arr[] = {10, 20, 10, 20, 30, 20, 20}
Output : 20

# Python3 program to find the most # frequent element in an array. def mostFrequent(arr, n): # Sort the array arr.sort() # find the max frequency using # linear traversal max_count = 1; res = arr[0]; curr_count = 1 for i in range(1, n): if (arr[i] == arr[i - 1]): curr_count += 1 else : if (curr_count > max_count): max_count = curr_count res = arr[i - 1] curr_count = 1
# If last element is most frequent if (curr_count > max_count): max_count = curr_count res = arr[n - 1] return res # Driver Code arr = [1, 5, 2, 1, 3, 2, 1] n = len(arr) print(mostFrequent(arr, n))

Output : 1

Write a program to print all palindromes in a given range
Given a range of numbers, print all palindromes in the given range. For example if the given range is {10, 115}, then output should be
{11, 22, 33, 44, 55, 66, 77, 88, 99, 101, 111}

# A function to check if n is palindrome def isPalindrome(n: int) -> bool: # Find reverse of n rev = 0 i = n while i > 0: rev = rev * 10 + i % 10 i //= 10 # If n and rev are same, # then n is palindrome return (n == rev)

# prints palindrome between min and max def countPal(minn: int, maxx: int) -> None: for i in range(minn, maxx + 1): if isPalindrome(i): print(i, end = " ")

# Driver Code if __name__ == "__main__": countPal(100, 200)

Output: 101 111 121 131 141 151 161 171 181 191

Program for Number to Words Conversion in Python Without Any Library # Number to Words # Main Logic ones = ('Zero', 'One', 'Two', 'Three', 'Four', 'Five', 'Six', 'Seven', 'Eight', 'Nine') twos = ('Ten', 'Eleven', 'Twelve', 'Thirteen', 'Fourteen', 'Fifteen', 'Sixteen', 'Seventeen', 'Eighteen', 'Nineteen') tens = ('Twenty', 'Thirty', 'Forty', 'Fifty', 'Sixty', 'Seventy', 'Eighty', 'Ninety', 'Hundred') suffixes = ('', 'Thousand', 'Million', 'Billion') def process(number, index): if number=='0': return 'Zero' length = len(number) if(length > 3): return False number = number.zfill(3) words = '' hdigit = int(number[0]) tdigit = int(number[1]) odigit = int(number[2]) words += '' if number[0] == '0' else ones[hdigit] words += ' Hundred ' if not words == '' else '' if(tdigit > 1): words += tens[tdigit - 2] words += ' ' words += ones[odigit] elif(tdigit == 1): words += twos[(int(tdigit + odigit) % 10) - 1] elif(tdigit == 0): words += ones[odigit] if(words.endswith('Zero')): words = words[:-len('Zero')] else: words += ' ' if(not len(words) == 0): words += suffixes[index] return words; def getWords(number): length = len(str(number)) if length>12: return 'This program supports upto 12 digit numbers.' count = length // 3 if length % 3 == 0 else length // 3 + 1 copy = count words = [] for i in range(length - 1, -1, -3): words.append(process(str(number)[0 if i - 2 < 0 else i - 2 : i + 1], copy - count)) count -= 1; final_words = '' for s in reversed(words): temp = s + ' ' final_words += temp return final_words # Reading number from user number = int(input('Enter any number: ')) print('%d in words is: %s' %(number, getWords(number)))

How to print Python dictionary into JSON format?
JSON stands for Javascript Standard Object Notation.
Python module called json is a JSON encoder/decoder.
The dumps() function in this module returns a JSON string representation of Python dictionary object.

D1={"pen":25, "pencil":10, "book":100, "sharpner":5, "eraser":5}
import json
j=json.dumps(D1)
j
'{"pen": 25, "pencil": 10, "book": 100, "sharpner": 5, "eraser": 5}'

2 comments:

  1. What happened to Python Interview question section ?

    https://okayguru.blogspot.com/2020/06/python-interview-question-question-bank.html

    This post is removed ?

    ReplyDelete