def Total_Hamming_Distance(n):
    i = 1
    sum = 0
    while (n // i > 0):
        sum = sum + n // i
        i = i * 2
    return sum

assert Total_Hamming_Distance(4) == 7
assert Total_Hamming_Distance(2) == 3
assert Total_Hamming_Distance(5) == 8

Write a python function to find the sum of hamming distances of all consecutive numbers from o to n.


def longest_increasing_subsequence(arr):
	n = len(arr)
	longest_increasing_subsequence = [1]*n
	for i in range (1 , n):
		for j in range(0 , i):
			if arr[i] > arr[j] and longest_increasing_subsequence[i]< longest_increasing_subsequence[j] + 1 :
				longest_increasing_subsequence[i] = longest_increasing_subsequence[j]+1
	maximum = 0
	for i in range(n):
		maximum = max(maximum , longest_increasing_subsequence[i])
	return maximum

assert longest_increasing_subsequence([10, 22, 9, 33, 21, 50, 41, 60]) == 5

assert longest_increasing_subsequence([3, 10, 2, 1, 20]) == 3

assert longest_increasing_subsequence([50, 3, 10, 7, 40, 80]) == 4

Write a function to find the length of the longest increasing subsequence of the given sequence.


def odd_Num_Sum(n) :
    j = 0
    sm = 0
    for i in range(1,n+1) :
        j = (2*i-1)
        sm = sm + (j*j*j*j*j)
    return sm

assert odd_Num_Sum(1) == 1
assert odd_Num_Sum(2) == 244
assert odd_Num_Sum(3) == 3369

Write a python function to find the sum of fifth power of first n odd natural numbers.


def find_Max(arr,low,high):
    if (high < low):
        return arr[0]
    if (high == low):
        return arr[low]
    mid = low + (high - low) // 2
    if (mid < high and arr[mid + 1] < arr[mid]):
        return arr[mid]
    if (mid > low and arr[mid] < arr[mid - 1]):
        return arr[mid - 1]
    if (arr[low] > arr[mid]):
        return find_Max(arr,low,mid - 1)
    else:
        return find_Max(arr,mid + 1,high)

Write a python function to find the maximum element in a sorted and rotated array.


def extract_column(list1, n):
   result = [i.pop(n) for i in list1]
   return result

Write a function to extract a specified column from a given nested list.


def Seq_Linear(seq_nums):
  seq_nums = [seq_nums[x] - seq_nums[x-1] for x in range(1, len(seq_nums))]
  if len(set(seq_nums)) == 1:
    return "Linear Sequence"
  else:
    return "Non Linear Sequence"

assert Seq_Linear([0,2,4,6,8,10]) == "Linear Sequence"

assert Seq_Linear([1,2,3]) == "Linear Sequence"

assert Seq_Linear([1,5,2]) == "Non Linear Sequence"

Write a python function to check whether a given sequence is linear or not.


def tuple_to_float(test_tup):
  res = float('.'.join(str(ele) for ele in test_tup))
  return (res)

assert tuple_to_float((7, 256)) == 7.256

assert tuple_to_float((8, 123)) == 8.123

Write a function to convert the given tuple to a floating-point number.


def Split(list):
    od_li = []
    for i in list:
        if (i % 2 != 0):
            od_li.append(i)
    return od_li

Write a python function to find odd numbers from a mixed list.


def difference(n) :
    S = (n*(n + 1))//2;
    res = S*(S-1);
    return res;

assert difference(3) == 30
assert difference(5) == 210
assert difference(2) == 6

Write a python function to find the difference between sum of cubes of first n natural numbers and the sum of first n natural numbers.


def find_Odd_Pair(A,N) :
    oddPair = 0
    for i in range(0,N) :
        for j in range(i+1,N) :
            if ((A[i] ^ A[j]) % 2 != 0):
                oddPair+=1
    return oddPair

Write a python function to count the pairs with xor as an odd number.


def toggle_string(string):
 string1 = string.swapcase()
 return string1

Write a function to toggle characters case in a string.


def digit_distance_nums(n1, n2):
         return sum(map(int,str(abs(n1-n2))))

assert digit_distance_nums(123,256) == 7

Write a python function to find the digit distance between two integers.


def max_sub_array_sum(a, size):
  max_so_far = 0
  max_ending_here = 0
  for i in range(0, size):
    max_ending_here = max_ending_here + a[i]
    if max_ending_here < 0:
      max_ending_here = 0
    elif (max_so_far < max_ending_here):
      max_so_far = max_ending_here
  return max_so_far

Write a function to find the largest sum of contiguous subarray in the given array.


def union_elements(test_tup1, test_tup2):
  res = tuple(set(test_tup1 + test_tup2))
  return (res)

Write a function to find the union of elements of the given tuples.


def assign_elements(test_list):
  res = dict()
  for key, val in test_list:
    res.setdefault(val, [])
    res.setdefault(key, []).append(val)
  return (res)

Write a function to assign with each element, its pair elements from other similar pairs in the given tuple.


def Find_Max_Length(lst):
    maxLength = max(len(x) for x in lst )
    return maxLength

Write a python function to find the maximum length of sublist.


import re
def extract_values(text):
 return (re.findall(r'"(.*?)"', text))

assert extract_values('"Python", "PHP", "Java"')==['Python', 'PHP', 'Java']

Write a function to extract values between quotation marks of a string.


def count_Pairs(arr,n):
    cnt = 0;
    for i in range(n):
        for j in range(i + 1,n):
            if (arr[i] != arr[j]):
                cnt += 1;
    return cnt;

Write a python function to count unequal element pairs from the given array.


def split(word):
    return [char for char in word]

assert split('Name') == ['N','a','m','e']

Write a python function to split a string into characters.


def sum_digits(n):
  if n == 0:
    return 0
  else:
    return n % 10 + sum_digits(int(n / 10))

assert sum_digits(345)==12
assert sum_digits(12)==3
assert sum_digits(97)==16

Write a function to get the sum of a non-negative integer.


def issort_list(list1):
    result = all(list1[i] <= list1[i+1] for i in range(len(list1)-1))
    return result

Write a function to check whether a specified list is sorted or not.


def empty_list(length):
 empty_list = [{} for _ in range(length)]
 return empty_list

Write a function to create a list of empty dictionaries.


def sort_sublists(list1):
    result = list(map(sorted,list1))
    return result

assert sort_sublists([['green', 'orange'], ['black', 'white'], ['white', 'black', 'orange']])==[['green', 'orange'], ['black', 'white'], ['black', 'orange', 'white']]

assert sort_sublists([['green', 'orange'], ['black'], ['green', 'orange'], ['white']])==[['green', 'orange'], ['black'], ['green', 'orange'], ['white']]

Write a function to sort each sublist of strings in a given list of lists.


def remove_words(list1, charlist):
    new_list = []
    for line in list1:
        new_words = ' '.join([word for word in line.split() if not any([phrase in word for phrase in charlist])])
        new_list.append(new_words)
    return new_list

assert remove_words(['Red color', 'Orange#', 'Green', 'Orange @', "White"],['#', 'color', '@'])==['Red', '', 'Green', 'Orange', 'White']

assert remove_words(['Red &', 'Orange+', 'Green', 'Orange @', 'White'],['&', '+', '@'])==['Red', '', 'Green', 'Orange', 'White']

assert remove_words(['Red &', 'Orange+', 'Green', 'Orange @', 'White'],['@'])==['Red &', 'Orange+', 'Green', 'Orange', 'White']

Write a function to remove words from a given list of strings containing a character or string.


def max_sum_pair_diff_lessthan_K(arr, N, K):
	arr.sort()
	dp = [0] * N
	dp[0] = 0
	for i in range(1, N):
		dp[i] = dp[i-1]
		if (arr[i] - arr[i-1] < K):
			if (i >= 2):
				dp[i] = max(dp[i], dp[i-2] + arr[i] + arr[i-1]);
			else:
				dp[i] = max(dp[i], arr[i] + arr[i-1]);
	return dp[N - 1]

assert max_sum_pair_diff_lessthan_K([5, 15, 10, 300], 4, 12) == 25

assert max_sum_pair_diff_lessthan_K([1, 2, 3, 4, 5, 6], 6, 6) == 21

Write a function to find maximum possible sum of disjoint pairs for the given array of integers and a number k.


def two_unique_nums(nums):
  return [i for i in nums if nums.count(i)==1]

Write a python function to remove two duplicate numbers from a given number of lists.


def unique_product(list_data):
    temp = list(set(list_data))
    p = 1
    for i in temp:
        p *= i
    return p

assert unique_product([1, 2, 3, 1,]) == 6

assert unique_product([7, 8, 9, 0, 1, 1]) == 0

Write a python function to calculate the product of the unique numbers of a given list.


def surfacearea_cylinder(r,h):
  surfacearea=((2*3.1415*r*r) +(2*3.1415*r*h))
  return surfacearea

Write a function to find the surface area of a cylinder.


def count_no (A,N,L,R):
    count = 0
    for i in range (L,R + 1):
        if (i % A != 0):
            count += 1
        if (count == N):
            break
    return (i)

Write a python function to find nth number in a sequence which is not a multiple of a given number.


def is_Sub_Array(A,B,n,m):
    i = 0; j = 0;
    while (i < n and j < m):
        if (A[i] == B[j]):
            i += 1;
            j += 1;
            if (j == m):
                return True;
        else:
            i = i - j + 1;
            j = 0;
    return False;

Write a python function to check whether an array is subarray of another or not.


def last_Digit_Factorial(n):
    if (n == 0): return 1
    elif (n <= 2): return n
    elif (n == 3): return 6
    elif (n == 4): return 4
    else:
      return 0

assert last_Digit_Factorial(4) == 4
assert last_Digit_Factorial(21) == 0
assert last_Digit_Factorial(30) == 0

Write a python function to find the last digit in factorial of a given number.


def interleave_lists(list1,list2,list3):
    result = [el for pair in zip(list1, list2, list3) for el in pair]
    return result

Write a function to interleave lists of the same length.


def find_dissimilar(test_tup1, test_tup2):
  res = tuple(set(test_tup1) ^ set(test_tup2))
  return (res)

Write a function to find the dissimilar elements in the given two tuples.


def even_ele(test_tuple, even_fnc):
	res = tuple()
	for ele in test_tuple:
		if isinstance(ele, tuple):
			res += (even_ele(ele, even_fnc), )
		elif even_fnc(ele):
			res += (ele, )
	return res
def extract_even(test_tuple):
  res = even_ele(test_tuple, lambda x: x % 2 == 0)
  return (res)

Write a function to extract the even elements in the nested mixed tuple.


def surface_Area(b,s):
    return 2 * b * s + pow(b,2)

assert surface_Area(3,4) == 33
assert surface_Area(4,5) == 56
assert surface_Area(1,2) == 5

Write a python function to find the surface area of the square pyramid.


def my_dict(dict1):
  if bool(dict1):
     return False
  else:
     return True

assert my_dict({10})==False
assert my_dict({11})==False
assert my_dict({})==True

Write a function to check if a dictionary is empty or not.


def catalan_number(num):
    if num <=1:
         return 1
    res_num = 0
    for i in range(num):
        res_num += catalan_number(i) * catalan_number(num-i-1)
    return res_num

assert catalan_number(10)==16796
assert catalan_number(9)==4862
assert catalan_number(7)==429

Write a function for nth catalan number.


import re
def find_adverbs(text):
  for m in re.finditer(r"\w+ly", text):
    return ('%d-%d: %s' % (m.start(), m.end(), m.group(0)))

assert find_adverbs("Clearly, he has no excuse for such behavior.") == '0-7: Clearly'

assert find_adverbs("Please handle the situation carefuly") == '28-36: carefuly'

assert find_adverbs("Complete the task quickly") == '18-25: quickly'

Write a function to find all adverbs and their positions in a given sentence by using regex.


import heapq
def expensive_items(items,n):
  expensive_items = heapq.nlargest(n, items, key=lambda s: s['price'])
  return expensive_items

Write a function to find the n - expensive price items from a given dataset using heap queue algorithm.


def split_Arr(a,n,k):
   b = a[:k]
   return (a[k::]+b[::])

Write a python function to split the array and add the first part to the end.


def list_tuple(listx):
  tuplex = tuple(listx)
  return tuplex

Write a function to convert a list to a tuple.


def big_diff(nums):
     diff= max(nums)-min(nums)
     return diff

Write a python function to find the difference between largest and smallest value in a given array.


def perfect_squares(a, b):
    lists=[]
    for i in range (a,b+1):
        j = 1;
        while j*j <= i:
            if j*j == i:
                 lists.append(i)
            j = j+1
        i = i+1
    return lists

Write a function to find perfect squares between two given numbers.


import cmath
def polar_rect(x,y):
 cn = complex(x,y)
 cn=cmath.polar(cn)
 cn1 = cmath.rect(2, cmath.pi)
 return (cn,cn1)

Write a function to convert polar coordinates to rectangular coordinates.


def swap_List(newList):
    size = len(newList)
    temp = newList[0]
    newList[0] = newList[size - 1]
    newList[size - 1] = temp
    return newList

Write a python function to interchange the first and last elements in a list.


def binomial_Coeff(n,k):
    C = [0] * (k + 1);
    C[0] = 1; # nC0 is 1
    for i in range(1,n + 1):
        for j in range(min(i, k),0,-1):
            C[j] = C[j] + C[j - 1];
    return C[k];
def sum_Of_product(n):
    return binomial_Coeff(2 * n,n - 1);

assert sum_Of_product(3) == 15
assert sum_Of_product(4) == 56
assert sum_Of_product(1) == 1

Write a python function to find sum of product of binomial co-efficients.


import re
def removezero_ip(ip):
 string = re.sub('\.[0]*', '.', ip)
 return string

Write a function to remove leading zeroes from an ip address.


def diff_even_odd(list1):
    first_even = next((el for el in list1 if el%2==0),-1)
    first_odd = next((el for el in list1 if el%2!=0),-1)
    return (first_even-first_odd)

Write a function to find the difference of first even and odd number of a given list.


def min_Swaps(str1,str2) :
    count = 0
    for i in range(len(str1)) :
        if str1[i] != str2[i] :
            count += 1
    if count % 2 == 0 :
        return (count // 2)
    else :
        return ("Not Possible")

assert min_Swaps("111","000") == "Not Possible"

assert min_Swaps("111","110") == "Not Possible"

Write a python function to count minimum number of swaps required to convert one binary string to another.


import sys
def tuple_size(tuple_list):
  return (sys.getsizeof(tuple_list))

assert tuple_size((1, "Raju", 2, "Nikhil", 3, "Deepanshu") ) == sys.getsizeof((1, "Raju", 2, "Nikhil", 3, "Deepanshu"))

Write a function to find the size of the given tuple.


def find_kth(arr1, arr2, m, n, k):
	sorted1 = [0] * (m + n)
	i = 0
	j = 0
	d = 0
	while (i < m and j < n):
		if (arr1[i] < arr2[j]):
			sorted1[d] = arr1[i]
			i += 1
		else:
			sorted1[d] = arr2[j]
			j += 1
		d += 1
	while (i < m):
		sorted1[d] = arr1[i]
		d += 1
		i += 1
	while (j < n):
		sorted1[d] = arr2[j]
		d += 1
		j += 1
	return sorted1[k - 1]

Write a function to find kth element from the given two sorted arrays.


def armstrong_number(number):
 sum = 0
 times = 0
 temp = number
 while temp > 0:
           times = times + 1
           temp = temp // 10
 temp = number
 while temp > 0:
           reminder = temp % 10
           sum = sum + (reminder ** times)
           temp //= 10
 if number == sum:
           return True
 else:
           return False

assert armstrong_number(153)==True
assert armstrong_number(259)==False
assert armstrong_number(4458)==False

Write a function to check whether the given number is armstrong or not.


def sum_average(number):
 total = 0
 for value in range(1, number + 1):
    total = total + value
 average = total / number
 return (total,average)

assert sum_average(10)==(55, 5.5)
assert sum_average(15)==(120, 8.0)
assert sum_average(20)==(210, 10.5)

Write a function to find sum and average of first n natural numbers.


def is_Even(n) :
    if (n^1 == n+1) :
        return True;
    else :
        return False;

assert is_Even(1) == False
assert is_Even(2) == True
assert is_Even(3) == False

Write a python function to check whether the given number is even or not using bitwise operator.


R = 3
C = 3
def min_cost(cost, m, n):
	tc = [[0 for x in range(C)] for x in range(R)]
	tc[0][0] = cost[0][0]
	for i in range(1, m+1):
		tc[i][0] = tc[i-1][0] + cost[i][0]
	for j in range(1, n+1):
		tc[0][j] = tc[0][j-1] + cost[0][j]
	for i in range(1, m+1):
		for j in range(1, n+1):
			tc[i][j] = min(tc[i-1][j-1], tc[i-1][j], tc[i][j-1]) + cost[i][j]
	return tc[m][n]

Write a function to find the minimum cost path to reach (m, n) from (0, 0) for the given cost matrix cost[][] and a position (m, n) in cost[][].


def similar_elements(test_tup1, test_tup2):
  res = tuple(set(test_tup1) & set(test_tup2))
  return (res)

Write a function to find the similar elements from the given two tuple lists.


import math
def is_not_prime(n):
    result = False
    for i in range(2,int(math.sqrt(n)) + 1):
        if n % i == 0:
            result = True
    return result

assert is_not_prime(2) == False
assert is_not_prime(10) == True
assert is_not_prime(35) == True

Write a python function to identify non-prime numbers.


import heapq as hq
def heap_queue_largest(nums,n):
  largest_nums = hq.nlargest(n, nums)
  return largest_nums

Write a function to find the largest integers from a given list of numbers using heap queue algorithm.


assert count_ways(2) == 3
assert count_ways(8) == 153
assert count_ways(12) == 2131

Write a function to find the number of ways to fill it with 2 x 1 dominoes for the given 3 x n board.


def is_Power_Of_Two (x):
    return x and (not(x & (x - 1)))
def differ_At_One_Bit_Pos(a,b):
    return is_Power_Of_Two(a ^ b)

assert differ_At_One_Bit_Pos(13,9) == True

assert differ_At_One_Bit_Pos(15,8) == False

assert differ_At_One_Bit_Pos(2,4) == False

Write a python function to check whether the two numbers differ at one bit position only or not.


import re
def find_char_long(text):
  return (re.findall(r"\b\w{4,}\b", text))

assert find_char_long('Please move back to stream') == ['Please', 'move', 'back', 'stream']

assert find_char_long('Jing Eco and Tech') == ['Jing', 'Tech']

assert find_char_long('Jhingai wulu road Zone 3') == ['Jhingai', 'wulu', 'road', 'Zone']

Write a function to find all words which are at least 4 characters long in a string by using regex.


def square_nums(nums):
 square_nums = list(map(lambda x: x ** 2, nums))
 return square_nums

Write a function to find squares of individual elements in a list using lambda function.


def find_Rotations(str):
    tmp = str + str
    n = len(str)
    for i in range(1,n + 1):
        substring = tmp[i: i+n]
        if (str == substring):
            return i
    return n

assert find_Rotations("aaaa") == 1
assert find_Rotations("ab") == 2
assert find_Rotations("abc") == 3

Write a python function to find the minimum number of rotations required to get the same string.


import heapq
def small_nnum(list1,n):
  smallest=heapq.nsmallest(n,list1)
  return smallest

Write a function to get the n smallest items from a dataset.