Write a function to find the specified number of largest products from two given lists.

def large_product(nums1, nums2, N):
    result = sorted([x*y for x in nums1 for y in nums2], reverse=True)[:N]
    return result


Write a python function to find the maximum of two numbers.

def maximum(a,b):
    if a >= b:
        return a
    else:
        return b

assert maximum(5,10) == 10
assert maximum(-1,-2) == -1
assert maximum(9,7) == 9


Write a function to convert a given string to a tuple.

def string_to_tuple(str1):
    result = tuple(x for x in str1 if not x.isspace())
    return result

assert string_to_tuple("item1")==('i', 't', 'e', 'm', '1')


Write a python function to set the left most unset bit.

def set_left_most_unset_bit(n):
    if not (n & (n + 1)):
        return n
    pos, temp, count = 0, n, 0
    while temp:
        if not (temp & 1):
            pos = count
        count += 1; temp>>=1
    return (n | (1 << (pos)))

assert set_left_most_unset_bit(10) == 14

assert set_left_most_unset_bit(12) == 14

assert set_left_most_unset_bit(15) == 15


Write a function to find the volume of a cone.

import math
def volume_cone(r,h):
  volume = (1.0/3) * math.pi * r * r * h
  return volume


Write a python function to print positive numbers in a list.

def pos_nos(list1):
  for num in list1:
    if num >= 0:
       return num


Write a function to find out the maximum sum such that no two chosen numbers are adjacent for the given rectangular grid of dimension 2 x n.

def max_sum_rectangular_grid(grid, n) :
	incl = max(grid[0][0], grid[1][0])
	excl = 0
	for i in range(1, n) :
		excl_new = max(excl, incl)
		incl = excl + max(grid[0][i], grid[1][i])
		excl = excl_new
	return max(excl, incl)

assert max_sum_rectangular_grid([ [1, 4, 5], [2, 0, 0 ] ], 3) == 7


Write a python function to find the first maximum length of even word.

def find_Max_Len_Even(str):
    n = len(str)
    i = 0
    currlen = 0
    maxlen = 0
    st = -1
    while (i < n):
        if (str[i] == ' '):
            if (currlen % 2 == 0):
                if (maxlen < currlen):
                    maxlen = currlen
                    st = i - currlen
            currlen = 0
        else :
            currlen += 1
        i += 1
    if (currlen % 2 == 0):
        if (maxlen < currlen):
            maxlen = currlen
            st = i - currlen
    if (st == -1):
        return "-1"
    return str[st: st + maxlen]

assert find_Max_Len_Even("python language") == "language"

assert find_Max_Len_Even("maximum even length") == "length"


Write a function to find the index of the last occurrence of a given number in a sorted array.

def find_last_occurrence(A, x):
    (left, right) = (0, len(A) - 1)
    result = -1
    while left <= right:
        mid = (left + right) // 2
        if x == A[mid]:
            result = mid
            left = mid + 1
        elif x < A[mid]:
            right = mid - 1
        else:
            left = mid + 1
    return result


Write a function to reflect the modified run-length encoding from a list.

from itertools import groupby
def modified_encode(alist):
        def ctr_ele(el):
            if len(el)>1: return [len(el), el[0]]
            else: return el[0]
        return [ctr_ele(list(group)) for key, group in groupby(alist)]

assert modified_encode('python')==['p', 'y', 't', 'h', 'o', 'n']


Write a python function to find the maximum volume of a cuboid with given sum of sides.

def max_volume (s):
    maxvalue = 0
    i = 1
    for i in range(s - 1):
        j = 1
        for j in range(s):
            k = s - i - j
            maxvalue = max(maxvalue, i * j * k)
    return maxvalue

assert max_volume(8) == 18
assert max_volume(4) == 2
assert max_volume(1) == 0


Write a function to find all five characters long word in the given string by using regex.

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

assert find_long_word('Please move back to strem') == ['strem']

assert find_long_word('4K Ultra HD streaming player') == ['Ultra']

assert find_long_word('Streaming Media Player') == ['Media']


Write a function to calculate the difference between the squared sum of first n natural numbers and the sum of squared first n natural numbers.

def sum_difference(n):
    sumofsquares = 0
    squareofsum = 0
    for num in range(1, n+1):
        sumofsquares += num * num
        squareofsum += num
    squareofsum = squareofsum ** 2
    return squareofsum - sumofsquares

assert sum_difference(12)==5434
assert sum_difference(20)==41230
assert sum_difference(54)==2151270


Write a function to find the demlo number for the given number.

def find_demlo(s):
	l = len(s)
	res = ""
	for i in range(1,l+1):
		res = res + str(i)
	for i in range(l-1,0,-1):
		res = res + str(i)
	return res


Write a function to find all index positions of the minimum values in a given list.

def position_min(list1):
    min_val = min(list1)
    min_result = [i for i, j in enumerate(list1) if j == min_val]
    return min_result


Write a function to re-arrange the given array in alternating positive and negative items.

def right_rotate(arr, n, out_of_place, cur):
	temp = arr[cur]
	for i in range(cur, out_of_place, -1):
		arr[i] = arr[i - 1]
	arr[out_of_place] = temp
	return arr
def re_arrange(arr, n):
	out_of_place = -1
	for index in range(n):
		if (out_of_place >= 0):
			if ((arr[index] >= 0 and arr[out_of_place] < 0) or
			(arr[index] < 0 and arr[out_of_place] >= 0)):
				arr = right_rotate(arr, n, out_of_place, index)
				if (index-out_of_place > 2):
					out_of_place += 2
				else:
					out_of_place = - 1
		if (out_of_place == -1):
			if ((arr[index] >= 0 and index % 2 == 0) or
			 (arr[index] < 0 and index % 2 == 1)):
				out_of_place = index
	return arr


Write a function to extract the sum of alternate chains of tuples.

def sum_of_alternates(test_tuple):
  sum1 = 0
  sum2 = 0
  for idx, ele in enumerate(test_tuple):
    if idx % 2:
      sum1 += ele
    else:
      sum2 += ele
  return ((sum1),(sum2))


Write a python function to find the minimum number of squares whose sum is equal to a given number.

def get_Min_Squares(n):
    if n <= 3:
        return n;
    res = n
    for x in range(1,n + 1):
        temp = x * x;
        if temp > n:
            break
        else:
            res = min(res,1 + get_Min_Squares(n  - temp))
    return res;

assert get_Min_Squares(6) == 3
assert get_Min_Squares(2) == 2
assert get_Min_Squares(4) == 1


Write a function to get the word with most number of occurrences in the given strings list.

from collections import defaultdict

def most_occurrences(test_list):
  temp = defaultdict(int)
  for sub in test_list:
    for wrd in sub.split():
      temp[wrd] += 1
  res = max(temp, key=temp.get)
  return (str(res))

assert most_occurrences(["UTS is best for RTF", "RTF love UTS", "UTS is best"] ) == 'UTS'

assert most_occurrences(["Its been a great year", "this year is so worse", "this year is okay"] ) == 'year'

assert most_occurrences(["Families can be reunited", "people can be reunited", "Tasks can be achieved "] ) == 'can'


Write a function to print check if the triangle is isosceles or not.

def check_isosceles(x,y,z):
  if x==y or y==z or z==x:
	   return True
  else:
     return False

assert check_isosceles(6,8,12)==False
assert check_isosceles(6,6,12)==True
assert check_isosceles(6,16,20)==False


Write a function to rotate a given list by specified number of items to the left direction.

def rotate_left(list1,m,n):
  result =  list1[m:]+list1[:n]
  return result


Write a python function to count negative numbers in a list.

def neg_count(list):
  neg_count= 0
  for num in list:
    if num <= 0:
      neg_count += 1
  return neg_count


Write a function to find all three, four, five characters long words in the given string by using regex.

import re
def find_char(text):
  return (re.findall(r"\b\w{3,5}\b", text))

assert find_char('For the four consumer complaints contact manager AKR reddy') == ['For', 'the', 'four', 'AKR', 'reddy']

assert find_char('Certain service are subject to change MSR') == ['are', 'MSR']

assert find_char('Third party legal desclaimers') == ['Third', 'party', 'legal']


Write a python function to count unset bits of a given number.

def count_unset_bits(n):
    count = 0
    x = 1
    while(x < n + 1):
        if ((x & n) == 0):
            count += 1
        x = x << 1
    return count

assert count_unset_bits(2) == 1
assert count_unset_bits(4) == 2
assert count_unset_bits(6) == 1


Write a function to count character frequency of a given string.

def char_frequency(str1):
    dict = {}
    for n in str1:
        keys = dict.keys()
        if n in keys:
            dict[n] += 1
        else:
            dict[n] = 1
    return dict


Write a python function to sort a list according to the second element in sublist.

def Sort(sub_li):
    sub_li.sort(key = lambda x: x[1])
    return sub_li


Write a python function to check whether the triangle is valid or not if sides are given.

def check_Validity(a,b,c):
    if (a + b <= c) or (a + c <= b) or (b + c <= a) :
        return False
    else:
        return True

assert check_Validity(1,2,3) == False
assert check_Validity(2,3,5) == False
assert check_Validity(7,10,5) == True


Write a function to find the sum of arithmetic progression.

def ap_sum(a,n,d):
  total = (n * (2 * a + (n - 1) * d)) / 2
  return total


Write a function to check whether the given month name contains 28 days or not.

def check_monthnum(monthname1):
  if monthname1 == "February":
    return True
  else:
    return False

assert check_monthnum("February")==True
assert check_monthnum("January")==False
assert check_monthnum("March")==False


Write a function that matches a word at the end of a string, with optional punctuation.

import re
def text_match_word(text):
        patterns = '\w+\S*$'
        if re.search(patterns,  text):
                return 'Found a match!'
        else:
                return 'Not matched!'

assert text_match_word("python.")==('Found a match!')

assert text_match_word("  lang  .")==('Not matched!')


Write a python function to count the number of substrings with same first and last characters.

def check_Equality(s):
    return (ord(s[0]) == ord(s[len(s) - 1]));
def count_Substring_With_Equal_Ends(s):
    result = 0;
    n = len(s);
    for i in range(n):
        for j in range(1,n-i+1):
            if (check_Equality(s[i:i+j])):
                result+=1;
    return result;

assert count_Substring_With_Equal_Ends('aba') == 4

assert count_Substring_With_Equal_Ends('abcab') == 7

assert count_Substring_With_Equal_Ends('abc') == 3


Write a python function to find the maximum occuring divisor in an interval.

def find_Divisor(x,y):
    if (x==y):
        return y
    return 2

assert find_Divisor(2,2) == 2
assert find_Divisor(2,5) == 2
assert find_Divisor(5,10) == 2


Write a python function to find the sum of the three lowest positive numbers from a given list of numbers.

def sum_three_smallest_nums(lst):
	return sum(sorted([x for x in lst if x > 0])[:3])

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

assert sum_three_smallest_nums([0,1,2,3,4,5]) == 6


Write a function to convert the given set into ordered tuples.

def set_to_tuple(s):
  t = tuple(sorted(s))
  return (t)


Write a function to find the smallest range that includes at-least one element from each of the given arrays.

from heapq import heappop, heappush
class Node:
    def __init__(self, value, list_num, index):
        self.value = value
        self.list_num = list_num
        self.index = index
    def __lt__(self, other):
        return self.value < other.value
def find_minimum_range(list):
    high = float('-inf')
    p = (0, float('inf'))
    pq = []
    for i in range(len(list)):
        heappush(pq, Node(list[i][0], i, 0))
        high = max(high, list[i][0])
    while True:
        top = heappop(pq)
        low = top.value
        i = top.list_num
        j = top.index
        if high - low < p[1] - p[0]:
            p = (low, high)
        if j == len(list[i]) - 1:
            return p
        heappush(pq, Node(list[i][j + 1], i, j + 1))
        high = max(high, list[i][j + 1])


Write a function to calculate the number of digits and letters in a string.

def dig_let(s):
 d=l=0
 for c in s:
    if c.isdigit():
        d=d+1
    elif c.isalpha():
        l=l+1
    else:
        pass
 return (l,d)

assert dig_let("python")==(6,0)
assert dig_let("program")==(7,0)
assert dig_let("python3.0")==(6,2)


Write a python function to find number of elements with odd factors in a given range.

def count_Odd_Squares(n,m):
    return int(m**0.5) - int((n-1)**0.5)

assert count_Odd_Squares(5,100) == 8
assert count_Odd_Squares(8,65) == 6
assert count_Odd_Squares(2,5) == 1


Write a function to find the difference between two consecutive numbers in a given list.

def diff_consecutivenums(nums):
    result = [b-a for a, b in zip(nums[:-1], nums[1:])]
    return result


Write a function to find entringer number e(n, k).

def zigzag(n, k):
	if (n == 0 and k == 0):
		return 1
	if (k == 0):
		return 0
	return zigzag(n, k - 1) + zigzag(n - 1, n - k)

assert zigzag(4, 3) == 5
assert zigzag(4, 2) == 4
assert zigzag(3, 1) == 1


Write a python function to count the number of squares in a rectangle.

def count_Squares(m,n):
    if (n < m):
        temp = m
        m = n
        n = temp
    return n * (n + 1) * (3 * m - n + 1) // 6

assert count_Squares(4,3) == 20
assert count_Squares(1,2) == 2
assert count_Squares(2,2) == 5


Write a function to count sequences of given length having non-negative prefix sums that can be generated by given values.

def bin_coff(n, r):
	val = 1
	if (r > (n - r)):
		r = (n - r)
	for i in range(0, r):
		val *= (n - i)
		val //= (i + 1)
	return val
def find_ways(M):
	n = M // 2
	a = bin_coff(2 * n, n)
	b = a // (n + 1)
	return (b)

assert find_ways(4) == 2
assert find_ways(6) == 5
assert find_ways(8) == 14


Write a python function to check whether the given string is a binary string or not.

def check(string) :
    p = set(string)
    s = {'0', '1'}
    if s == p or p == {'0'} or p == {'1'}:
        return ("Yes")
    else :
        return ("No")

assert check("01010101010") == "Yes"
assert check("name0") == "No"
assert check("101") == "Yes"


Write a python function to minimize the length of the string by removing occurrence of only one character.

def minimum_Length(s) :
    maxOcc = 0
    n = len(s)
    arr = [0]*26
    for i in range(n) :
        arr[ord(s[i]) -ord('a')] += 1
    for i in range(26) :
        if arr[i] > maxOcc :
            maxOcc = arr[i]
    return n - maxOcc

assert minimum_Length("mnm") == 1
assert minimum_Length("abcda") == 3
assert minimum_Length("abcb") == 2


Write a python function to find the first element occurring k times in a given array.

def first_Element(arr,n,k):
    count_map = {};
    for i in range(0, n):
        if(arr[i] in count_map.keys()):
            count_map[arr[i]] += 1
        else:
            count_map[arr[i]] = 1
        i += 1
    for i in range(0, n):
        if (count_map[arr[i]] == k):
            return arr[i]
        i += 1
    return -1


Write a python function to check whether all the characters in a given string are unique.

def unique_Characters(str):
    for i in range(len(str)):
        for j in range(i + 1,len(str)):
            if (str[i] == str[j]):
                return False;
    return True;

assert unique_Characters('aba') == False

assert unique_Characters('abab') == False


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

def remove_column(list1, n):
   for i in list1:
    del i[n]
   return list1


Write a function to find t-nth term of arithemetic progression.

def tn_ap(a,n,d):
  tn = a + (n - 1) * d
  return tn


Write a python function to count the number of rectangles in a circle of radius r.

def count_Rectangles(radius):
    rectangles = 0
    diameter = 2 * radius
    diameterSquare = diameter * diameter
    for a in range(1, 2 * radius):
        for b in range(1, 2 * radius):
            diagnalLengthSquare = (a * a +  b * b)
            if (diagnalLengthSquare <= diameterSquare) :
                rectangles += 1
    return rectangles

assert count_Rectangles(2) == 8
assert count_Rectangles(1) == 1
assert count_Rectangles(0) == 0


Write a function to find the third angle of a triangle using two angles.

def find_angle(a,b):
 c = 180 - (a + b)
 return c

assert find_angle(47,89)==44
assert find_angle(45,95)==40
assert find_angle(50,40)==90


Write a function to find the maximum element of all the given tuple records.

def find_max(test_list):
  res = max(int(j) for i in test_list for j in i)
  return (res)


Write a function to find modulo division of two lists using map and lambda function.

def moddiv_list(nums1,nums2):
  result = map(lambda x, y: x % y, nums1, nums2)
  return list(result)


Write a python function to check whether one root of the quadratic equation is twice of the other or not.

def Check_Solution(a,b,c):
    if (2*b*b == 9*a*c):
        return ("Yes");
    else:
        return ("No");

assert Check_Solution(1,3,2) == "Yes"
assert Check_Solution(1,2,3) == "No"
assert Check_Solution(1,-5,6) == "No"


Write a function to find the n’th carol number.

def get_carol(n):
	result = (2**n) - 1
	return result * result - 2

assert get_carol(2) == 7
assert get_carol(4) == 223
assert get_carol(5) == 959


Write a function to remove empty lists from a given list of lists.

def remove_empty(list1):
  remove_empty = [x for x in list1 if x]
  return remove_empty

assert remove_empty([[], [], [], 'Python',[],[], 'programming', 'language',[],[],[], [], []])==['Python', 'programming', 'language']


Write a python function to find the item with maximum occurrences in a given list.

def max_occurrences(nums):
    max_val = 0
    result = nums[0]
    for i in nums:
        occu = nums.count(i)
        if occu > max_val:
            max_val = occu
            result = i
    return result


Write a function to add the k elements to each element in the tuple.

def add_K_element(test_list, K):
  res = [tuple(j + K for j in sub ) for sub in test_list]
  return (res)


Write a function to find the number of flips required to make the given binary string a sequence of alternate characters.

def make_flip(ch):
	return '1' if (ch == '0') else '0'
def get_flip_with_starting_charcter(str, expected):
	flip_count = 0
	for i in range(len( str)):
		if (str[i] != expected):
			flip_count += 1
		expected = make_flip(expected)
	return flip_count
def min_flip_to_make_string_alternate(str):
	return min(get_flip_with_starting_charcter(str, '0'),get_flip_with_starting_charcter(str, '1'))

assert min_flip_to_make_string_alternate("0001010111") == 2

assert min_flip_to_make_string_alternate("001") == 1

assert min_flip_to_make_string_alternate("010111011") == 2


Write a python function to count the number of digits of a given number.

def count_Digit(n):
    count = 0
    while n != 0:
        n //= 10
        count += 1
    return count

assert count_Digit(12345) == 5
assert count_Digit(11223305) == 8
assert count_Digit(4123459) == 7


Write a python function to find the largest product of the pair of adjacent elements from a given list of integers.

def adjacent_num_product(list_nums):
    return max(a*b for a, b in zip(list_nums, list_nums[1:]))

assert adjacent_num_product([1,2,3,4,5,6]) == 30

assert adjacent_num_product([1,2,3,4,5]) == 20


Write a function to check if a binary tree is balanced or not.

class Node:
	def __init__(self, data):
		self.data = data
		self.left = None
		self.right = None
def get_height(root):
	if root is None:
		return 0
	return max(get_height(root.left), get_height(root.right)) + 1
def is_tree_balanced(root):
	if root is None:
		return True
	lh = get_height(root.left)
	rh = get_height(root.right)
	if (abs(lh - rh) <= 1) and is_tree_balanced(
	root.left) is True and is_tree_balanced( root.right) is True:
		return True
	return False

root = Node(1)
root.left = Node(2)
root.right = Node(3)
root.left.left = Node(4)
root.left.right = Node(5)
root.left.left.left = Node(8)
root1 = Node(1)
root1.left = Node(2)
root1.right = Node(3)
root1.left.left = Node(4)
root1.left.right = Node(5)
root1.right.left = Node(6)
root1.left.left.left = Node(7)
root2 = Node(1)
root2.left = Node(2)
root2.right = Node(3)
root2.left.left = Node(4)
root2.left.right = Node(5)
root2.left.left.left = Node(7)


Write a function to repeat the given tuple n times.

def repeat_tuples(test_tup, N):
  res = ((test_tup, ) * N)
  return (res)


Write a function to find the lateral surface area of cuboid

def lateralsurface_cuboid(l,w,h):
  LSA = 2*h*(l+w)
  return LSA


Write a function to sort a tuple by its float element.

def float_sort(price):
  float_sort=sorted(price, key=lambda x: float(x[1]), reverse=True)
  return float_sort


Write a function to find the smallest missing element in a sorted array.

def smallest_missing(A, left_element, right_element):
    if left_element > right_element:
        return left_element
    mid = left_element + (right_element - left_element) // 2
    if A[mid] == mid:
        return smallest_missing(A, mid + 1, right_element)
    else:
        return smallest_missing(A, left_element, mid - 1)


Write a function to sort a given list of elements in ascending order using heap queue algorithm.

import heapq as hq
def heap_assending(nums):
  hq.heapify(nums)
  s_result = [hq.heappop(nums) for i in range(len(nums))]
  return s_result


Write a function to find the volume of a cuboid.

def volume_cuboid(l,w,h):
  volume=l*w*h
  return volume

assert volume_cuboid(1,2,3)==6
assert volume_cuboid(5,7,9)==315
assert volume_cuboid(10,15,21)==3150


Write a function to print all permutations of a given string including duplicates.

def permute_string(str):
    if len(str) == 0:
        return ['']
    prev_list = permute_string(str[1:len(str)])
    next_list = []
    for i in range(0,len(prev_list)):
        for j in range(0,len(str)):
            new_str = prev_list[i][0:j]+str[0]+prev_list[i][j:len(str)-1]
            if new_str not in next_list:
                next_list.append(new_str)
    return next_list

assert permute_string('abc')==['abc', 'bac', 'bca', 'acb', 'cab', 'cba']

assert permute_string('abcd')==['abcd', 'bacd', 'bcad', 'bcda', 'acbd', 'cabd', 'cbad', 'cbda', 'acdb', 'cadb', 'cdab', 'cdba', 'abdc', 'badc', 'bdac', 'bdca', 'adbc', 'dabc', 'dbac', 'dbca', 'adcb', 'dacb', 'dcab', 'dcba']


Write a function to round the given number to the nearest multiple of a specific number.

def round_num(n,m):
    a = (n //m) * m
    b = a + m
    return (b if n - a > b - n else a)


Write a function to remove tuple elements that occur more than once and replace the duplicates with some custom value.

def remove_replica(test_tup):
  temp = set()
  res = tuple(ele if ele not in temp and not temp.add(ele)
				else 'MSP' for ele in test_tup)
  return (res)


Write a python function to remove all occurrences of a character in a given string.

def remove_Char(s,c) :
    counts = s.count(c)
    s = list(s)
    while counts :
        s.remove(c)
        counts -= 1
    s = '' . join(s)
    return (s)

assert remove_Char("toggle",'g') == "tole"

assert remove_Char("aabbc",'b') == "aac"


Write a python function to shift last element to first position in the given list.

def move_first(test_list):
  test_list = test_list[-1:] + test_list[:-1]
  return test_list


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

def surfacearea_cuboid(l,w,h):
  SA = 2*(l*w + l * h + w * h)
  return SA


Write a function to generate a two-dimensional array.

def multi_list(rownum,colnum):
  multi_list = [[0 for col in range(colnum)] for row in range(rownum)]
  for row in range(rownum):
    for col in range(colnum):
        multi_list[row][col]= row*col
  return multi_list


Write a function to sort a list of lists by a given index of the inner list.

from operator import itemgetter
def index_on_inner_list(list_data, index_no):
    result = sorted(list_data, key=itemgetter(index_no))
    return result

assert index_on_inner_list([('Greyson Fulton', 98, 99), ('Brady Kent', 97, 96), ('Wyatt Knott', 91, 94), ('Beau Turnbull', 94, 98)] ,0)==[('Beau Turnbull', 94, 98), ('Brady Kent', 97, 96), ('Greyson Fulton', 98, 99), ('Wyatt Knott', 91, 94)]

assert index_on_inner_list([('Greyson Fulton', 98, 99), ('Brady Kent', 97, 96), ('Wyatt Knott', 91, 94), ('Beau Turnbull', 94, 98)] ,1)==[('Wyatt Knott', 91, 94), ('Beau Turnbull', 94, 98), ('Brady Kent', 97, 96), ('Greyson Fulton', 98, 99)]

assert index_on_inner_list([('Greyson Fulton', 98, 99), ('Brady Kent', 97, 96), ('Wyatt Knott', 91, 94), ('Beau Turnbull', 94, 98)] ,2)==[('Wyatt Knott', 91, 94), ('Brady Kent', 97, 96), ('Beau Turnbull', 94, 98), ('Greyson Fulton', 98, 99)]


Write a function to find the number of rotations in a circularly sorted array.

def find_rotation_count(A):
    (left, right) = (0, len(A) - 1)
    while left <= right:
        if A[left] <= A[right]:
            return left
        mid = (left + right) // 2
        next = (mid + 1) % len(A)
        prev = (mid - 1 + len(A)) % len(A)
        if A[mid] <= A[next] and A[mid] <= A[prev]:
            return mid
        elif A[mid] <= A[right]:
            right = mid - 1
        elif A[mid] >= A[left]:
            left = mid + 1
    return -1

assert find_rotation_count([8, 9, 10,2, 5, 6]) == 3

assert find_rotation_count([2, 5, 6, 8, 9, 10]) == 0


Write a python function to toggle all odd bits of a given number.

def even_bit_toggle_number(n) :
    res = 0; count = 0; temp = n
    while(temp > 0 ) :
        if (count % 2 == 0) :
            res = res | (1 << count)
        count = count + 1
        temp >>= 1
    return n ^ res

assert even_bit_toggle_number(10) == 15
assert even_bit_toggle_number(20) == 1
assert even_bit_toggle_number(30) == 11


Write a python function to find the frequency of the smallest value in a given array.

def frequency_Of_Smallest(n,arr):
    mn = arr[0]
    freq = 1
    for i in range(1,n):
        if (arr[i] < mn):
            mn = arr[i]
            freq = 1
        elif (arr[i] == mn):
            freq += 1
    return freq

assert frequency_Of_Smallest(5,[1,2,3,4,3]) == 1

assert frequency_Of_Smallest(7,[3,1,2,5,6,2,3]) == 1

assert frequency_Of_Smallest(7,[3,3,6,3,7,4,9]) == 3


Write a function to find the n'th perrin number using recursion.

def get_perrin(n):
  if (n == 0):
    return 3
  if (n == 1):
    return 0
  if (n == 2):
    return 2
  return get_perrin(n - 2) + get_perrin(n - 3)

assert get_perrin(9) == 12
assert get_perrin(4) == 2
assert get_perrin(6) == 5


Write a function to find out the minimum no of swaps required for bracket balancing in the given string.

def swap_count(s):
	chars = s
	count_left = 0
	count_right = 0
	swap = 0
	imbalance = 0;
	for i in range(len(chars)):
		if chars[i] == '[':
			count_left += 1
			if imbalance > 0:
				swap += imbalance
				imbalance -= 1
		elif chars[i] == ']':
			count_right += 1
			imbalance = (count_right - count_left)
	return swap

assert swap_count("[]][][") == 2
assert swap_count("[[][]]") == 0
assert swap_count("[[][]]][") == 1


Write a python function to check whether the hexadecimal number is even or odd.

assert even_or_odd("AB3454D") =="Odd"
assert even_or_odd("ABC") == "Even"
assert even_or_odd("AAD") == "Odd"


Write a python function to find the highest power of 2 that is less than or equal to n.

def highest_Power_of_2(n):
    res = 0;
    for i in range(n, 0, -1):
        if ((i & (i - 1)) == 0):
            res = i;
            break;
    return res;

assert highest_Power_of_2(10) == 8
assert highest_Power_of_2(19) == 16
assert highest_Power_of_2(32) == 32


Write a function to find the n'th lucas number.

def find_lucas(n):
	if (n == 0):
		return 2
	if (n == 1):
		return 1
	return find_lucas(n - 1) + find_lucas(n - 2)

assert find_lucas(9) == 76
assert find_lucas(4) == 7
assert find_lucas(3) == 4


Write a function to insert a given string at the beginning of all items in a list.

def add_string(list,string):
 add_string=[string.format(i) for i in  list]
 return add_string

assert add_string(['a','b','c','d'], 'python{0}')==[ 'pythona', 'pythonb', 'pythonc', 'pythond']

assert add_string([5,6,7,8],'string{0}')==['string5', 'string6', 'string7', 'string8']


Write a function to convert more than one list to nested dictionary.

def convert_list_dictionary(l1, l2, l3):
     result = [{x: {y: z}} for (x, y, z) in zip(l1, l2, l3)]
     return result


Write a function to find the maximum sum possible by using the given equation f(n) = max( (f(n/2) + f(n/3) + f(n/4) + f(n/5)), n).

def get_max_sum (n):
	res = list()
	res.append(0)
	res.append(1)
	i = 2
	while i<n + 1:
		res.append(max(i, (res[int(i / 2)]
						+ res[int(i / 3)] +
							res[int(i / 4)]
						+ res[int(i / 5)])))
		i = i + 1
	return res[n]

assert get_max_sum(60) == 106
assert get_max_sum(10) == 12
assert get_max_sum(2) == 2


Write a function to find the list with maximum length using lambda function.

def max_length_list(input_list):
    max_length = max(len(x) for x in input_list )
    max_list = max(input_list, key = lambda i: len(i))
    return(max_length, max_list)


Write a function to check if given tuple is distinct or not.

def check_distinct(test_tup):
  res = True
  temp = set()
  for ele in test_tup:
    if ele in temp:
      res = False
      break
    temp.add(ele)
  return (res)

assert check_distinct((1, 4, 5, 6, 1, 4)) == False

assert check_distinct((1, 4, 5, 6)) == True

assert check_distinct((2, 3, 4, 5, 6)) == True


Write a python function to find the first non-repeated character in a given string.

def first_non_repeating_character(str1):
  char_order = []
  ctr = {}
  for c in str1:
    if c in ctr:
      ctr[c] += 1
    else:
      ctr[c] = 1
      char_order.append(c)
  for c in char_order:
    if ctr[c] == 1:
      return c
  return None

assert first_non_repeating_character("abcabc") == None

assert first_non_repeating_character("abc") == "a"

assert first_non_repeating_character("ababc") == "c"


Write a function to check whether the given string starts and ends with the same character or not using regex.

import re
regex = r'^[a-z]$|^([a-z]).*\1$'
def check_char(string):
	if(re.search(regex, string)):
		return "Valid"
	else:
		return "Invalid"

assert check_char("abba") == "Valid"
assert check_char("a") == "Valid"
assert check_char("abcd") == "Invalid"


Write a function to find the median of three specific numbers.

def median_numbers(a,b,c):
 if a > b:
    if a < c:
        median = a
    elif b > c:
        median = b
    else:
        median = c
 else:
    if a > c:
        median = a
    elif b < c:
        median = b
    else:
        median = c
 return median

assert median_numbers(25,55,65)==55.0
assert median_numbers(20,10,30)==20.0
assert median_numbers(15,45,75)==45.0


Write a function to compute the sum of digits of each number of a given list.

def sum_of_digits(nums):
    return sum(int(el) for n in nums for el in str(n) if el.isdigit())


Write a function to perform the mathematical bitwise xor operation across the given tuples.

def bitwise_xor(test_tup1, test_tup2):
  res = tuple(ele1 ^ ele2 for ele1, ele2 in zip(test_tup1, test_tup2))
  return (res)


Write a function to extract the frequency of unique tuples in the given list order irrespective.

def extract_freq(test_list):
  res = len(list(set(tuple(sorted(sub)) for sub in test_list)))
  return (res)


Write a function to perform index wise addition of tuple elements in the given two nested tuples.

def add_nested_tuples(test_tup1, test_tup2):
  res = tuple(tuple(a + b for a, b in zip(tup1, tup2))
   for tup1, tup2 in zip(test_tup1, test_tup2))
  return (res)


Write a function to compute the value of ncr%p.

def ncr_modp(n, r, p):
    C = [0 for i in range(r+1)]
    C[0] = 1
    for i in range(1, n+1):
        for j in range(min(i, r), 0, -1):
            C[j] = (C[j] + C[j-1]) % p
    return C[r]


Write a function to check if a url is valid or not using regex.

import re
def is_valid_URL(str):
	regex = ("((http|https)://)(www.)?" +
			"[a-zA-Z0-9@:%._\\+~#?&//=]" +
			"{2,256}\\.[a-z]" +
			"{2,6}\\b([-a-zA-Z0-9@:%" +
			"._\\+~#?&//=]*)")
	p = re.compile(regex)
	if (str == None):
		return False
	if(re.search(p, str)):
		return True
	else:
		return False

assert is_valid_URL("https://www.google.com") == True

assert is_valid_URL("https:/www.gmail.com") == False

assert is_valid_URL("https:// www.redit.com") == False


Write a python function to find the minimum of two numbers.

def minimum(a,b):
    if a <= b:
        return a
    else:
        return b

assert minimum(1,2) == 1
assert minimum(-5,-4) == -5
assert minimum(0,0) == 0


Write a function to check whether an element exists within a tuple.

def check_tuplex(tuplex,tuple1):
  if tuple1 in tuplex:
    return True
  else:
     return False


Write a python function to find the parity of a given number.

def find_Parity(x):
    y = x ^ (x >> 1);
    y = y ^ (y >> 2);
    y = y ^ (y >> 4);
    y = y ^ (y >> 8);
    y = y ^ (y >> 16);
    if (y & 1):
        return ("Odd Parity");
    return ("Even Parity");

assert find_Parity(12) == "Even Parity"
assert find_Parity(7) == "Odd Parity"
assert find_Parity(10) == "Even Parity"


Write a function to create the next bigger number by rearranging the digits of a given number.

def rearrange_bigger(n):
    nums = list(str(n))
    for i in range(len(nums)-2,-1,-1):
        if nums[i] < nums[i+1]:
            z = nums[i:]
            y = min(filter(lambda x: x > z[0], z))
            z.remove(y)
            z.sort()
            nums[i:] = [y] + z
            return int("".join(nums))
    return False

assert rearrange_bigger(12)==21
assert rearrange_bigger(10)==False
assert rearrange_bigger(102)==120


Write a function to find k number of pairs which consist of one element from the first array and one element from the second array.

import heapq
def k_smallest_pairs(nums1, nums2, k):
   queue = []
   def push(i, j):
       if i < len(nums1) and j < len(nums2):
           heapq.heappush(queue, [nums1[i] + nums2[j], i, j])
   push(0, 0)
   pairs = []
   while queue and len(pairs) < k:
       _, i, j = heapq.heappop(queue)
       pairs.append([nums1[i], nums2[j]])
       push(i, j + 1)
       if j == 0:
           push(i + 1, 0)
   return pairs


Write a function to find the minimum product from the pairs of tuples within a given list.

def min_product_tuple(list1):
    result_min = min([abs(x * y) for x, y in list1] )
    return result_min


Write a function to find the minimum value in a given heterogeneous list.

def min_val(listval):
     min_val = min(i for i in listval if isinstance(i, int))
     return min_val

assert min_val(['Python', 3, 2, 4, 5, 'version'])==2


Write a function to convert the given snake case string to camel case string by using regex.

import re
def snake_to_camel(word):
  return ''.join(x.capitalize() or '_' for x in word.split('_'))

assert snake_to_camel('android_tv') == 'AndroidTv'

assert snake_to_camel('google_pixel') == 'GooglePixel'

assert snake_to_camel('apple_watch') == 'AppleWatch'


Write a python function to remove odd numbers from a given list.

def remove_odd(l):
    for i in l:
        if i % 2 != 0:
            l.remove(i)
    return l


Write a function to extract the nth element from a given list of tuples.

def extract_nth_element(list1, n):
    result = [x[n] for x in list1]
    return result

assert extract_nth_element([('Greyson Fulton', 98, 99), ('Brady Kent', 97, 96), ('Wyatt Knott', 91, 94), ('Beau Turnbull', 94, 98)] ,0)==['Greyson Fulton', 'Brady Kent', 'Wyatt Knott', 'Beau Turnbull']

assert extract_nth_element([('Greyson Fulton', 98, 99), ('Brady Kent', 97, 96), ('Wyatt Knott', 91, 94), ('Beau Turnbull', 94, 98)] ,2)==[99, 96, 94, 98]

assert extract_nth_element([('Greyson Fulton', 98, 99), ('Brady Kent', 97, 96), ('Wyatt Knott', 91, 94), ('Beau Turnbull', 94, 98)],1)==[98, 97, 91, 94]


Write a python function to check whether the value exists in a sequence or not.

def overlapping(list1,list2):
    c=0
    d=0
    for i in list1:
        c+=1
    for i in list2:
        d+=1
    for i in range(0,c):
        for j in range(0,d):
            if(list1[i]==list2[j]):
                return 1
    return 0

assert overlapping([1,2,3],[4,5,6]) == False

assert overlapping([1,4,5],[1,4,5]) == True


Write a python function to find a pair with highest product from a given array of integers.

def max_Product(arr):
    arr_len = len(arr)
    if (arr_len < 2):
        return ("No pairs exists")
    x = arr[0]; y = arr[1]
    for i in range(0,arr_len):
        for j in range(i + 1,arr_len):
            if (arr[i] * arr[j] > x * y):
                x = arr[i]; y = arr[j]
    return x,y


Write a function to find the maximum sum we can make by dividing number in three parts recursively and summing them up together for the given number.

MAX = 1000000
def breakSum(n):
	dp = [0]*(n+1)
	dp[0] = 0
	dp[1] = 1
	for i in range(2, n+1):
		dp[i] = max(dp[int(i/2)] + dp[int(i/3)] + dp[int(i/4)], i);
	return dp[n]

assert breakSum(12) == 13
assert breakSum(24) == 27
assert breakSum(23) == 23


Write a function to find common first element in given list of tuple.

def group_tuples(Input):
	out = {}
	for elem in Input:
		try:
			out[elem[0]].extend(elem[1:])
		except KeyError:
			out[elem[0]] = list(elem)
	return [tuple(values) for values in out.values()]


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

def Find_Max(lst):
    maxList = max((x) for x in lst)
    return maxList


Write a function to round every number of a given list of numbers and print the total sum multiplied by the length of the list.

def round_and_sum(list1):
  lenght=len(list1)
  round_and_sum=sum(list(map(round,list1))* lenght)
  return round_and_sum


Write a python function to find the cube sum of first n even natural numbers.

def cube_Sum(n):
    sum = 0
    for i in range(1,n + 1):
        sum += (2*i)*(2*i)*(2*i)
    return sum

assert cube_Sum(2) == 72
assert cube_Sum(3) == 288
assert cube_Sum(4) == 800


Write a function to concatenate each element of tuple by the delimiter.

def concatenate_tuple(test_tup):
    delim = "-"
    res = ''.join([str(ele) + delim for ele in test_tup])
    res = res[ : len(res) - len(delim)]
    return (str(res))

assert concatenate_tuple(("ID", "is", 4, "UTS") ) == 'ID-is-4-UTS'

assert concatenate_tuple(("QWE", "is", 4, "RTY") ) == 'QWE-is-4-RTY'

assert concatenate_tuple(("ZEN", "is", 4, "OP") ) == 'ZEN-is-4-OP'


Write a python function to find the average of cubes of first n natural numbers.

def find_Average_Of_Cube(n):
    sum = 0
    for i in range(1, n + 1):
        sum += i * i * i
    return round(sum / n, 6)

assert find_Average_Of_Cube(2) == 4.5
assert find_Average_Of_Cube(3) == 12
assert find_Average_Of_Cube(1) == 1


Write a function to solve gold mine problem.

def get_maxgold(gold, m, n):
    goldTable = [[0 for i in range(n)]
                        for j in range(m)]
    for col in range(n-1, -1, -1):
        for row in range(m):
            if (col == n-1):
                right = 0
            else:
                right = goldTable[row][col+1]
            if (row == 0 or col == n-1):
                right_up = 0
            else:
                right_up = goldTable[row-1][col+1]
            if (row == m-1 or col == n-1):
                right_down = 0
            else:
                right_down = goldTable[row+1][col+1]
            goldTable[row][col] = gold[row][col] + max(right, right_up, right_down)
    res = goldTable[0][0]
    for i in range(1, m):
        res = max(res, goldTable[i][0])
    return res


Write a function to extract only the rear index element of each string in the given tuple.

def extract_rear(test_tuple):
  res = list(sub[len(sub) - 1] for sub in test_tuple)
  return (res)

assert extract_rear(('Mers', 'for', 'Vers') ) == ['s', 'r', 's']

assert extract_rear(('Avenge', 'for', 'People') ) == ['e', 'r', 'e']

assert extract_rear(('Gotta', 'get', 'go') ) == ['a', 't', 'o']


Write a function to count the number of sublists containing a particular element.

def count_element_in_list(list1, x):
    ctr = 0
    for i in range(len(list1)):
        if x in list1[i]:
            ctr+= 1
    return ctr


Write a function to filter odd numbers using lambda function.

def filter_oddnumbers(nums):
 odd_nums = list(filter(lambda x: x%2 != 0, nums))
 return odd_nums


Write a function to convert a date of yyyy-mm-dd format to dd-mm-yyyy format by using regex.


Write a function to sort the given array by using shell sort.

def shell_sort(my_list):
    gap = len(my_list) // 2
    while gap > 0:
        for i in range(gap, len(my_list)):
            current_item = my_list[i]
            j = i
            while j >= gap and my_list[j - gap] > current_item:
                my_list[j] = my_list[j - gap]
                j -= gap
            my_list[j] = current_item
        gap //= 2

    return my_list


Write a function to extract the elementwise and tuples from the given two tuples.

def and_tuples(test_tup1, test_tup2):
  res = tuple(ele1 & ele2 for ele1, ele2 in zip(test_tup1, test_tup2))
  return (res)


Write a function to find the directrix of a parabola.

def parabola_directrix(a, b, c):
  directrix=((int)(c - ((b * b) + 1) * 4 * a ))
  return directrix

assert parabola_directrix(5,3,2)==-198
assert parabola_directrix(9,8,4)==-2336
assert parabola_directrix(2,4,6)==-130


Write a function that takes two lists and returns true if they have at least one common element.

def common_element(list1, list2):
     result = False
     for x in list1:
         for y in list2:
             if x == y:
                 result = True
                 return result


Write a function to find the median of a trapezium.

def median_trapezium(base1,base2,height):
 median = 0.5 * (base1+ base2)
 return median

assert median_trapezium(15,25,35)==20
assert median_trapezium(10,20,30)==15
assert median_trapezium(6,9,4)==7.5


Write a function to check whether the entered number is greater than the elements of the given array.

def check_greater(arr, number):
  arr.sort()
  if number > arr[-1]:
    return ('Yes, the entered number is greater than those in the array')
  else:
    return ('No, entered number is less than those in the array')

assert check_greater([1, 2, 3, 4, 5], 4) == 'No, entered number is less than those in the array'

assert check_greater([2, 3, 4, 5, 6], 8) == 'Yes, the entered number is greater than those in the array'

assert check_greater([9, 7, 4, 8, 6, 1], 11) == 'Yes, the entered number is greater than those in the array'


Write a function that matches a string that has an a followed by one or more b's.

import re
def text_match_one(text):
        patterns = 'ab+?'
        if re.search(patterns,  text):
                return 'Found a match!'
        else:
                return('Not matched!')

assert text_match_one("abba")==('Found a match!')


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

assert last_Digit(123) == 3
assert last_Digit(25) == 5
assert last_Digit(30) == 0


Write a python function to print negative numbers in a list.

def neg_nos(list1):
  for num in list1:
    if num < 0:
       return num


Write a function to remove odd characters in a string.

def remove_odd(str1):
 str2 = ''
 for i in range(1, len(str1) + 1):
    if(i % 2 == 0):
        str2 = str2 + str1[i - 1]
 return str2

assert remove_odd("python")==("yhn")
assert remove_odd("program")==("rga")
assert remove_odd("language")==("agae")


Write a function to count bidirectional tuple pairs.

def count_bidirectional(test_list):
  res = 0
  for idx in range(0, len(test_list)):
    for iidx in range(idx + 1, len(test_list)):
      if test_list[iidx][0] == test_list[idx][1] and test_list[idx][1] == test_list[iidx][0]:
        res += 1
  return (str(res))


Write a function to convert a list of multiple integers into a single integer.

def multiple_to_single(L):
  x = int("".join(map(str, L)))
  return x

assert multiple_to_single([11, 33, 50])==113350


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

import re
def find_adverb_position(text):
 for m in re.finditer(r"\w+ly", text):
    return (m.start(), m.end(), m.group(0))

assert find_adverb_position("clearly!! we can see the sky")==(0, 7, 'clearly')

assert find_adverb_position("seriously!! there are many roses")==(0, 9, 'seriously')

assert find_adverb_position("unfortunately!! sita is going to home")==(0, 13, 'unfortunately')


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

def surfacearea_cube(l):
  surfacearea= 6*l*l
  return surfacearea

assert surfacearea_cube(5)==150
assert surfacearea_cube(3)==54
assert surfacearea_cube(10)==600


Write a function to find the ration of positive numbers in an array of integers.

from array import array
def positive_count(nums):
    n = len(nums)
    n1 = 0
    for x in nums:
        if x > 0:
            n1 += 1
        else:
          None
    return round(n1/n,2)


Write a python function to find the largest negative number from the given list.

def largest_neg(list1):
    max = list1[0]
    for x in list1:
        if x < max :
             max = x
    return max


Write a function to trim each tuple by k in the given tuple list.

def trim_tuple(test_list, K):
  res = []
  for ele in test_list:
    N = len(ele)
    res.append(tuple(list(ele)[K: N - K]))
  return (str(res))


Write a function to perform index wise multiplication of tuple elements in the given two tuples.

def index_multiplication(test_tup1, test_tup2):
  res = tuple(tuple(a * b for a, b in zip(tup1, tup2))
   for tup1, tup2 in zip(test_tup1, test_tup2))
  return (res)


Write a python function to count the occurence of all elements of list in a tuple.

from collections import Counter
def count_Occurrence(tup, lst):
    count = 0
    for item in tup:
        if item in lst:
            count+= 1
    return count


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

def cube_nums(nums):
 cube_nums = list(map(lambda x: x ** 3, nums))
 return cube_nums


Write a function to calculate the sum of perrin numbers.

def cal_sum(n):
	a = 3
	b = 0
	c = 2
	if (n == 0):
		return 3
	if (n == 1):
		return 3
	if (n == 2):
		return 5
	sum = 5
	while (n > 2):
		d = a + b
		sum = sum + d
		a = b
		b = c
		c = d
		n = n-1
	return sum

assert cal_sum(9) == 49
assert cal_sum(10) == 66
assert cal_sum(11) == 88


Write a python function to check whether the triangle is valid or not if 3 points are given.

def check_Triangle(x1,y1,x2,y2,x3,y3):
    a = (x1*(y2-y3)+x2*(y3-y1)+x3*(y1-y2))
    if a == 0:
        return ('No')
    else:
        return ('Yes')

assert check_Triangle(1,5,2,5,4,6) == 'Yes'

assert check_Triangle(1,1,1,4,1,5) == 'No'

assert check_Triangle(1,1,1,1,1,1) == 'No'


Write a function to extract specified size of strings from a give list of string values.

def extract_string(str, l):
    result = [e for e in str if len(e) == l]
    return result

assert extract_string(['Python', 'list', 'exercises', 'practice', 'solution'] ,8)==['practice', 'solution']

assert extract_string(['Python', 'list', 'exercises', 'practice', 'solution'] ,6)==['Python']

assert extract_string(['Python', 'list', 'exercises', 'practice', 'solution'] ,9)==['exercises']


Write a function to remove all whitespaces from the given string using regex.

import re
def remove_whitespaces(text1):
  return (re.sub(r'\s+', '',text1))

assert remove_whitespaces(' Google    Flutter ') == 'GoogleFlutter'

assert remove_whitespaces(' Google    Dart ') == 'GoogleDart'

assert remove_whitespaces(' iOS    Swift ') == 'iOSSwift'


Write a function that gives loss amount if the given amount has loss else return none.

def loss_amount(actual_cost,sale_amount):
  if(sale_amount > actual_cost):
    amount = sale_amount - actual_cost
    return amount
  else:
    return None

assert loss_amount(1500,1200)==None
assert loss_amount(100,200)==100
assert loss_amount(2000,5000)==3000


Write a python function to find the sum of even factors of a number.

import math
def sumofFactors(n) :
    if (n % 2 != 0) :
        return 0
    res = 1
    for i in range(2, (int)(math.sqrt(n)) + 1) :
        count = 0
        curr_sum = 1
        curr_term = 1
        while (n % i == 0) :
            count= count + 1
            n = n // i
            if (i == 2 and count == 1) :
                curr_sum = 0
            curr_term = curr_term * i
            curr_sum = curr_sum + curr_term
        res = res * curr_sum
    if (n >= 2) :
        res = res * (1 + n)
    return res

assert sumofFactors(18) == 26
assert sumofFactors(30) == 48
assert sumofFactors(6) == 8


Write a function that matches a word containing 'z'.

import re
def text_match_wordz(text):
        patterns = '\w*z.\w*'
        if re.search(patterns,  text):
                return 'Found a match!'
        else:
                return('Not matched!')

assert text_match_wordz("pythonz.")==('Found a match!')

assert text_match_wordz("xyz.")==('Found a match!')

assert text_match_wordz("  lang  .")==('Not matched!')


Write a function to check whether the given month number contains 31 days or not.

def check_monthnumb_number(monthnum2):
  if(monthnum2==1 or monthnum2==3 or monthnum2==5 or monthnum2==7 or monthnum2==8 or monthnum2==10 or monthnum2==12):
    return True
  else:
    return False

assert check_monthnumb_number(5)==True
assert check_monthnumb_number(2)==False
assert check_monthnumb_number(6)==False


Write a function to reverse strings in a given list of string values.

def reverse_string_list(stringlist):
    result = [x[::-1] for x in stringlist]
    return result

assert reverse_string_list(['Red', 'Green', 'Blue', 'White', 'Black'])==['deR', 'neerG', 'eulB', 'etihW', 'kcalB']


Write a python function to find the sublist having minimum length.

def Find_Min(lst):
    minList = min((x) for x in lst)
    return minList


Write a function to find the area of a rectangle.

def rectangle_area(l,b):
  area=l*b
  return area

assert rectangle_area(10,20)==200
assert rectangle_area(10,5)==50
assert rectangle_area(4,2)==8


Write a function to remove uppercase substrings from a given string by using regex.

import re
def remove_uppercase(str1):
  remove_upper = lambda text: re.sub('[A-Z]', '', text)
  result =  remove_upper(str1)
  return (result)

assert remove_uppercase('cAstyoUrFavoRitETVshoWs') == 'cstyoravoitshos'

assert remove_uppercase('wAtchTheinTernEtrAdIo') == 'wtchheinerntrdo'

assert remove_uppercase('VoicESeaRchAndreComMendaTionS') == 'oiceachndreomendaion'


Write a python function to get the first element of each sublist.

def Extract(lst):
    return [item[0] for item in lst]


Write a python function to count the upper case characters in a given string.

def upper_ctr(str):
    upper_ctr = 0
    for i in range(len(str)):
          if str[i] >= 'A' and str[i] <= 'Z': upper_ctr += 1
          return upper_ctr

assert upper_ctr('PYthon') == 1
assert upper_ctr('BigData') == 1
assert upper_ctr('program') == 0


Write a function to find all possible combinations of the elements of a given list.

def combinations_list(list1):
    if len(list1) == 0:
        return [[]]
    result = []
    for el in combinations_list(list1[1:]):
        result += [el, el+[list1[0]]]
    return result

assert combinations_list(['orange', 'red', 'green', 'blue'])==[[], ['orange'], ['red'], ['red', 'orange'], ['green'], ['green', 'orange'], ['green', 'red'], ['green', 'red', 'orange'], ['blue'], ['blue', 'orange'], ['blue', 'red'], ['blue', 'red', 'orange'], ['blue', 'green'], ['blue', 'green', 'orange'], ['blue', 'green', 'red'], ['blue', 'green', 'red', 'orange']]

assert combinations_list(['red', 'green', 'blue', 'white', 'black', 'orange'])==[[], ['red'], ['green'], ['green', 'red'], ['blue'], ['blue', 'red'], ['blue', 'green'], ['blue', 'green', 'red'], ['white'], ['white', 'red'], ['white', 'green'], ['white', 'green', 'red'], ['white', 'blue'], ['white', 'blue', 'red'], ['white', 'blue', 'green'], ['white', 'blue', 'green', 'red'], ['black'], ['black', 'red'], ['black', 'green'], ['black', 'green', 'red'], ['black', 'blue'], ['black', 'blue', 'red'], ['black', 'blue', 'green'], ['black', 'blue', 'green', 'red'], ['black', 'white'], ['black', 'white', 'red'], ['black', 'white', 'green'], ['black', 'white', 'green', 'red'], ['black', 'white', 'blue'], ['black', 'white', 'blue', 'red'], ['black', 'white', 'blue', 'green'], ['black', 'white', 'blue', 'green', 'red'], ['orange'], ['orange', 'red'], ['orange', 'green'], ['orange', 'green', 'red'], ['orange', 'blue'], ['orange', 'blue', 'red'], ['orange', 'blue', 'green'], ['orange', 'blue', 'green', 'red'], ['orange', 'white'], ['orange', 'white', 'red'], ['orange', 'white', 'green'], ['orange', 'white', 'green', 'red'], ['orange', 'white', 'blue'], ['orange', 'white', 'blue', 'red'], ['orange', 'white', 'blue', 'green'], ['orange', 'white', 'blue', 'green', 'red'], ['orange', 'black'], ['orange', 'black', 'red'], ['orange', 'black', 'green'], ['orange', 'black', 'green', 'red'], ['orange', 'black', 'blue'], ['orange', 'black', 'blue', 'red'], ['orange', 'black', 'blue', 'green'], ['orange', 'black', 'blue', 'green', 'red'], ['orange', 'black', 'white'], ['orange', 'black', 'white', 'red'], ['orange', 'black', 'white', 'green'], ['orange', 'black', 'white', 'green', 'red'], ['orange', 'black', 'white', 'blue'], ['orange', 'black', 'white', 'blue', 'red'], ['orange', 'black', 'white', 'blue', 'green'], ['orange', 'black', 'white', 'blue', 'green', 'red']]

assert combinations_list(['red', 'green', 'black', 'orange'])==[[], ['red'], ['green'], ['green', 'red'], ['black'], ['black', 'red'], ['black', 'green'], ['black', 'green', 'red'], ['orange'], ['orange', 'red'], ['orange', 'green'], ['orange', 'green', 'red'], ['orange', 'black'], ['orange', 'black', 'red'], ['orange', 'black', 'green'], ['orange', 'black', 'green', 'red']]


Write a function to find the maximum product subarray of the given array.

def max_subarray_product(arr):
	n = len(arr)
	max_ending_here = 1
	min_ending_here = 1
	max_so_far = 0
	flag = 0
	for i in range(0, n):
		if arr[i] > 0:
			max_ending_here = max_ending_here * arr[i]
			min_ending_here = min (min_ending_here * arr[i], 1)
			flag = 1
		elif arr[i] == 0:
			max_ending_here = 1
			min_ending_here = 1
		else:
			temp = max_ending_here
			max_ending_here = max (min_ending_here * arr[i], 1)
			min_ending_here = temp * arr[i]
		if (max_so_far < max_ending_here):
			max_so_far = max_ending_here
	if flag == 0 and max_so_far == 0:
		return 0
	return max_so_far

assert max_subarray_product([6, -3, -10, 0, 2]) == 180

assert max_subarray_product([-2, -40, 0, -2, -3]) == 80


Write a function to check if all values are same in a dictionary.

def check_value(dict, n):
    result = all(x == n for x in dict.values())
    return result

assert check_value({'Cierra Vega': 12, 'Alden Cantrell': 12, 'Kierra Gentry': 12, 'Pierre Cox': 12},10)==False

assert check_value({'Cierra Vega': 12, 'Alden Cantrell': 12, 'Kierra Gentry': 12, 'Pierre Cox': 12},12)==True

assert check_value({'Cierra Vega': 12, 'Alden Cantrell': 12, 'Kierra Gentry': 12, 'Pierre Cox': 12},5)==False


Write a function to drop empty items from a given dictionary.

def drop_empty(dict1):
  dict1 = {key:value for (key, value) in dict1.items() if value is not None}
  return dict1

assert drop_empty({'c1': 'Red', 'c2': 'Green', 'c3':None})=={'c1': 'Red', 'c2': 'Green'}

assert drop_empty({'c1': 'Red', 'c2': None, 'c3':None})=={'c1': 'Red'}

assert drop_empty({'c1': None, 'c2': 'Green', 'c3':None})=={ 'c2': 'Green'}


Write a function to find the peak element in the given array.

def find_peak_util(arr, low, high, n):
	mid = low + (high - low)/2
	mid = int(mid)
	if ((mid == 0 or arr[mid - 1] <= arr[mid]) and
		(mid == n - 1 or arr[mid + 1] <= arr[mid])):
		return mid
	elif (mid > 0 and arr[mid - 1] > arr[mid]):
		return find_peak_util(arr, low, (mid - 1), n)
	else:
		return find_peak_util(arr, (mid + 1), high, n)
def find_peak(arr, n):
	return find_peak_util(arr, 0, n - 1, n)


Write a python function to convert decimal number to octal number.

def decimal_to_Octal(deciNum):
    octalNum = 0
    countval = 1;
    dNo = deciNum;
    while (deciNum!= 0):
        remainder= deciNum % 8;
        octalNum+= remainder*countval;
        countval= countval*10;
        deciNum //= 8;
    return (octalNum)

assert decimal_to_Octal(10) == 12
assert decimal_to_Octal(2) == 2
assert decimal_to_Octal(33) == 41


Write a function to find the maximum product formed by multiplying numbers of an increasing subsequence of that array.

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


Write a function to find the maximum profit earned from a maximum of k stock transactions

def max_profit(price, k):
    n = len(price)
    final_profit = [[None for x in range(n)] for y in range(k + 1)]
    for i in range(k + 1):
        for j in range(n):
            if i == 0 or j == 0:
                final_profit[i][j] = 0
            else:
                max_so_far = 0
                for x in range(j):
                    curr_price = price[j] - price[x] + final_profit[i-1][x]
                    if max_so_far < curr_price:
                        max_so_far = curr_price
                final_profit[i][j] = max(final_profit[i][j-1], max_so_far)
    return final_profit[k][n-1]


Write a function to find the pairwise addition of the elements of the given tuples.

def add_pairwise(test_tup):
  res = tuple(i + j for i, j in zip(test_tup, test_tup[1:]))
  return (res)


Write a python function to find remainder of array multiplication divided by n.

def find_remainder(arr, lens, n):
    mul = 1
    for i in range(lens):
        mul = (mul * (arr[i] % n)) % n
    return mul % n


Write a python function to check whether the given list contains consecutive numbers or not.

def check_Consecutive(l):
    return sorted(l) == list(range(min(l),max(l)+1))

assert check_Consecutive([1,2,3,4,5]) == True

assert check_Consecutive([1,2,3,5,6]) == False

assert check_Consecutive([1,2,1]) == False


Write a function to find the tuple intersection of elements in the given tuple list irrespective of their order.

def tuple_intersection(test_list1, test_list2):
  res = set([tuple(sorted(ele)) for ele in test_list1]) & set([tuple(sorted(ele)) for ele in test_list2])
  return (res)


Write a function to replace characters in a string.

def replace_char(str1,ch,newch):
 str2 = str1.replace(ch, newch)
 return str2


Write a function to sort counter by value.

from collections import Counter
def sort_counter(dict1):
 x = Counter(dict1)
 sort_counter=x.most_common()
 return sort_counter

assert sort_counter({'Math':81, 'Physics':83, 'Chemistry':87})==[('Chemistry', 87), ('Physics', 83), ('Math', 81)]

assert sort_counter({'Math':400, 'Physics':300, 'Chemistry':250})==[('Math', 400), ('Physics', 300), ('Chemistry', 250)]


Write a python function to find the sum of the largest and smallest value in a given array.

def big_sum(nums):
      sum= max(nums)+min(nums)
      return sum


Write a python function to convert the given string to lower case.

def is_lower(string):
  return (string.lower())

assert is_lower("SenTenCE") == "sentence"


Write a function to remove lowercase substrings from a given string.

import re
def remove_lowercase(str1):
 remove_lower = lambda text: re.sub('[a-z]', '', text)
 result =  remove_lower(str1)
 return result


Write a python function to find the first digit of a given number.

def first_Digit(n) :
    while n >= 10:
        n = n / 10;
    return int(n)

assert first_Digit(123) == 1
assert first_Digit(456) == 4
assert first_Digit(12) == 1


Write a python function to find the maximum occurring character in a given string.

def get_max_occuring_char(str1):
  ASCII_SIZE = 256
  ctr = [0] * ASCII_SIZE
  max = -1
  ch = ''
  for i in str1:
    ctr[ord(i)]+=1;
  for i in str1:
    if max < ctr[ord(i)]:
      max = ctr[ord(i)]
      ch = i
  return ch

assert get_max_occuring_char("data") == "a"

assert get_max_occuring_char("create") == "e"

assert get_max_occuring_char("brilliant girl") == "i"


Write a function to determine if there is a subset of the given set with sum equal to the given sum.

def is_subset_sum(set, n, sum):
	if (sum == 0):
		return True
	if (n == 0):
		return False
	if (set[n - 1] > sum):
		return is_subset_sum(set, n - 1, sum)
	return is_subset_sum(set, n-1, sum) or is_subset_sum(set, n-1, sum-set[n-1])


Write a function to find sequences of one upper case letter followed by lower case letters in the given string by using regex.

import re
def match(text):
		pattern = '[A-Z]+[a-z]+$'
		if re.search(pattern, text):
				return('Yes')
		else:
				return('No')

assert match("Geeks") == 'Yes'
assert match("geeksforGeeks") == 'Yes'
assert match("geeks") == 'No'


Write a python function to find the first natural number whose factorial is divisible by x.

def first_Factorial_Divisible_Number(x):
    i = 1;
    fact = 1;
    for i in range(1,x):
        fact = fact * i
        if (fact % x == 0):
            break
    return i

assert first_Factorial_Divisible_Number(10) == 5

assert first_Factorial_Divisible_Number(15) == 5

assert first_Factorial_Divisible_Number(5) == 4


Write a function to remove the matching tuples from the given two tuples.

def remove_matching_tuple(test_list1, test_list2):
  res = [sub for sub in test_list1 if sub not in test_list2]
  return (res)

assert remove_matching_tuple([('Hello', 'dude'), ('How', 'are'), ('you', '?')], [('Hello', 'dude'), ('How', 'are')]) == [('you', '?')]

assert remove_matching_tuple([('Part', 'of'), ('the', 'journey'), ('is ', 'end')], [('Journey', 'the'), ('is', 'end')]) == [('Part', 'of'), ('the', 'journey'), ('is ', 'end')]

assert remove_matching_tuple([('Its', 'been'), ('a', 'long'), ('day', 'without')], [('a', 'long'), ('my', 'friend')]) == [('Its', 'been'), ('day', 'without')]


Write a function to find the largest palindromic number in the given array.

def is_palindrome(n) :
	divisor = 1
	while (n / divisor >= 10) :
		divisor *= 10
	while (n != 0) :
		leading = n // divisor
		trailing = n % 10
		if (leading != trailing) :
			return False
		n = (n % divisor) // 10
		divisor = divisor // 100
	return True
def largest_palindrome(A, n) :
	A.sort()
	for i in range(n - 1, -1, -1) :
		if (is_palindrome(A[i])) :
			return A[i]
	return -1

assert largest_palindrome([1, 2, 3, 4, 5, 50], 6) == 5

assert largest_palindrome([1, 3, 7, 9, 45], 5)  == 9


Write a function to compute binomial probability for the given number.

def nCr(n, r):
	if (r > n / 2):
		r = n - r
	answer = 1
	for i in range(1, r + 1):
		answer *= (n - r + i)
		answer /= i
	return answer
def binomial_probability(n, k, p):
	return (nCr(n, k) * pow(p, k) *	pow(1 - p, n - k))


Write a function to sort a list of tuples in increasing order by the last element in each tuple.

def sort_tuple(tup):
	lst = len(tup)
	for i in range(0, lst):
		for j in range(0, lst-i-1):
			if (tup[j][-1] > tup[j + 1][-1]):
				temp = tup[j]
				tup[j]= tup[j + 1]
				tup[j + 1]= temp
	return tup


Write a function to find the area of a pentagon.

import math
def area_pentagon(a):
  area=(math.sqrt(5*(5+2*math.sqrt(5)))*pow(a,2))/4.0
  return area


Write a python function to find the frequency of the largest value in a given array.

def frequency_Of_Largest(n,arr):
    mn = arr[0]
    freq = 1
    for i in range(1,n):
        if (arr[i] >mn):
            mn = arr[i]
            freq = 1
        elif (arr[i] == mn):
            freq += 1
    return freq

assert frequency_Of_Largest(5,[1,2,3,4,4]) == 2

assert frequency_Of_Largest(3,[5,6,5]) == 1

assert frequency_Of_Largest(4,[2,7,7,7]) == 3


Write a function to extract all the pairs which are symmetric in the given tuple list.

def extract_symmetric(test_list):
  temp = set(test_list) & {(b, a) for a, b in test_list}
  res = {(a, b) for a, b in temp if a < b}
  return (res)


Write a function to find the sum of geometric progression series.

import math
def sum_gp(a,n,r):
 total = (a * (1 - math.pow(r, n ))) / (1- r)
 return total


Write a function to search an element in the given array by using binary search.

def binary_search(item_list,item):
	first = 0
	last = len(item_list)-1
	found = False
	while( first<=last and not found):
		mid = (first + last)//2
		if item_list[mid] == item :
			found = True
		else:
			if item < item_list[mid]:
				last = mid - 1
			else:
				first = mid + 1
	return found

assert binary_search([1,2,3,5,8], 6) == False

assert binary_search([7, 8, 9, 10, 13], 10) == True


Write a function to calculate a grid of hexagon coordinates where function returns a list of lists containing 6 tuples of x, y point coordinates.

import math
def calculate_polygons(startx, starty, endx, endy, radius):
    sl = (2 * radius) * math.tan(math.pi / 6)
    p = sl * 0.5
    b = sl * math.cos(math.radians(30))
    w = b * 2
    h = 2 * sl
    startx = startx - w
    starty = starty - h
    endx = endx + w
    endy = endy + h
    origx = startx
    origy = starty
    xoffset = b
    yoffset = 3 * p
    polygons = []
    row = 1
    counter = 0
    while starty < endy:
        if row % 2 == 0:
            startx = origx + xoffset
        else:
            startx = origx
        while startx < endx:
            p1x = startx
            p1y = starty + p
            p2x = startx
            p2y = starty + (3 * p)
            p3x = startx + b
            p3y = starty + h
            p4x = startx + w
            p4y = starty + (3 * p)
            p5x = startx + w
            p5y = starty + p
            p6x = startx + b
            p6y = starty
            poly = [
                (p1x, p1y),
                (p2x, p2y),
                (p3x, p3y),
                (p4x, p4y),
                (p5x, p5y),
                (p6x, p6y),
                (p1x, p1y)]
            polygons.append(poly)
            counter += 1
            startx += w
        starty += yoffset
        row += 1
    return polygons


Write a function to convert the given binary tuple to integer.

def binary_to_integer(test_tup):
  res = int("".join(str(ele) for ele in test_tup), 2)
  return (str(res))


Write a function to remove lowercase substrings from a given string by using regex.

import re
def remove_lowercase(str1):
  remove_lower = lambda text: re.sub('[a-z]', '', text)
  result =  remove_lower(str1)
  return (result)

assert remove_lowercase('KDeoALOklOOHserfLoAJSIskdsf') == 'KDALOOOHLAJSI'

assert remove_lowercase('ProducTnamEstreAmIngMediAplAYer') == 'PTEAIMAAY'

assert remove_lowercase('maNufacTuredbYSheZenTechNolOGIes') == 'NTYSZTNOGI'


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

import heapq as hq
def heap_queue_smallest(nums,n):
  smallest_nums = hq.nsmallest(n, nums)
  return smallest_nums


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

import math
def surfacearea_cone(r,h):
  l = math.sqrt(r * r + h * h)
  SA = math.pi * r * (r + l)
  return SA


Write a python function to find gcd of two positive integers.

def gcd(x, y):
    gcd = 1
    if x % y == 0:
        return y
    for k in range(int(y / 2), 0, -1):
        if x % k == 0 and y % k == 0:
            gcd = k
            break
    return gcd

assert gcd(12, 17) == 1
assert gcd(4,6) == 2
assert gcd(2,9) == 1


Write a function to find the diameter of a circle.

def diameter_circle(r):
  diameter=2*r
  return diameter

assert diameter_circle(10)==20
assert diameter_circle(40)==80
assert diameter_circle(15)==30


Write a function to concatenate all elements of the given list into a string.

def concatenate_elements(list):
  ans = ' '
  for i in list:
    ans = ans+ ' '+i
  return (ans)

assert concatenate_elements(['hello','there','have','a','rocky','day'] ) == '  hello there have a rocky day'

assert concatenate_elements([ 'Hi', 'there', 'How','are', 'you'] ) == '  Hi there How are you'

assert concatenate_elements([ 'Part', 'of', 'the','journey', 'is', 'end'] ) == '  Part of the journey is end'


Write a python function to find common divisor between two numbers in a given pair.

def ngcd(x,y):
    i=1
    while(i<=x and i<=y):
        if(x%i==0 and y%i == 0):
            gcd=i;
        i+=1
    return gcd;
def num_comm_div(x,y):
  n = ngcd(x,y)
  result = 0
  z = int(n**0.5)
  i = 1
  while(i <= z):
    if(n % i == 0):
      result += 2
      if(i == n/i):
        result-=1
    i+=1
  return result

assert num_comm_div(2,4) == 2
assert num_comm_div(2,8) == 2
assert num_comm_div(12,24) == 6


Write a python function to find remainder of two numbers.

assert find(3,3) == 0
assert find(10,3) == 1
assert find(16,5) == 1


Write a function to add consecutive numbers of a given list.

def add_consecutive_nums(nums):
    result = [b+a for a, b in zip(nums[:-1], nums[1:])]
    return result


Write a python function to find the cube sum of first n natural numbers.

def sum_Of_Series(n):
    sum = 0
    for i in range(1,n + 1):
        sum += i * i*i
    return sum

assert sum_Of_Series(5) == 225
assert sum_Of_Series(2) == 9
assert sum_Of_Series(3) == 36


Write a function to move all zeroes to the end of the given array.

def re_order(A):
    k = 0
    for i in A:
        if i:
            A[k] = i
            k = k + 1
    for i in range(k, len(A)):
        A[i] = 0
    return A


Write a function to calculate the permutation coefficient of given p(n, k).

def permutation_coefficient(n, k):
	P = [[0 for i in range(k + 1)]
			for j in range(n + 1)]
	for i in range(n + 1):
		for j in range(min(i, k) + 1):
			if (j == 0):
				P[i][j] = 1
			else:
				P[i][j] = P[i - 1][j] + (
						j * P[i - 1][j - 1])
			if (j < k):
				P[i][j + 1] = 0
	return P[n][k]

assert permutation_coefficient(10, 2) == 90

assert permutation_coefficient(10, 3) == 720

assert permutation_coefficient(10, 1) == 10


Write a function to remove specific words from a given list.

def remove_words(list1, removewords):
    for word in list(list1):
        if word in removewords:
            list1.remove(word)
    return list1

assert remove_words(['red', 'green', 'blue', 'white', 'black', 'orange'],['white', 'orange'])==['red', 'green', 'blue', 'black']

assert remove_words(['red', 'green', 'blue', 'white', 'black', 'orange'],['black', 'orange'])==['red', 'green', 'blue', 'white']

assert remove_words(['red', 'green', 'blue', 'white', 'black', 'orange'],['blue', 'white'])==['red', 'green', 'black', 'orange']


Write a function to check if the common elements between two given lists are in the same order or not.

def same_order(l1, l2):
    common_elements = set(l1) & set(l2)
    l1 = [e for e in l1 if e in common_elements]
    l2 = [e for e in l2 if e in common_elements]
    return l1 == l2


Write a python function to find the average of odd numbers till a given odd number.

def average_Odd(n) :
    if (n%2==0) :
        return ("Invalid Input")
        return -1
    sm =0
    count =0
    while (n>=1) :
        count=count+1
        sm = sm + n
        n = n-2
    return sm//count

assert average_Odd(9) == 5
assert average_Odd(5) == 3
assert average_Odd(11) == 6


Write a function to find the number of subsequences having product smaller than k for the given non negative array.

def no_of_subsequences(arr, k):
	n = len(arr)
	dp = [[0 for i in range(n + 1)]
			for j in range(k + 1)]
	for i in range(1, k + 1):
		for j in range(1, n + 1):
			dp[i][j] = dp[i][j - 1]
			if arr[j - 1] <= i and arr[j - 1] > 0:
				dp[i][j] += dp[i // arr[j - 1]][j - 1] + 1
	return dp[k][n]

assert no_of_subsequences([1,2,3,4], 10) == 11

assert no_of_subsequences([4,8,7,2], 50) == 9

assert no_of_subsequences([5,6,7,8], 15) == 4


Write a python function to find minimum sum of factors of a given number.

def find_Min_Sum(num):
    sum = 0
    i = 2
    while(i * i <= num):
        while(num % i == 0):
            sum += i
            num /= i
        i += 1
    sum += num
    return sum

assert find_Min_Sum(12) == 7
assert find_Min_Sum(105) == 15
assert find_Min_Sum(2) == 2


Write a function to count the element frequency in the mixed nested tuple.

def flatten(test_tuple):
	for tup in test_tuple:
		if isinstance(tup, tuple):
			yield from flatten(tup)
		else:
			yield tup
def count_element_freq(test_tuple):
  res = {}
  for ele in flatten(test_tuple):
    if ele not in res:
      res[ele] = 0
    res[ele] += 1
  return (res)


Write a function to convert tuple into list by adding the given string after every element.

def add_str(test_tup, K):
  res = [ele for sub in test_tup for ele in (sub, K)]
  return (res)


Write a function to find the summation of tuple elements in the given tuple list.

def sum_elements(test_tup):
  res = sum(list(test_tup))
  return (res)


Write a function to check if there is a subset with sum divisible by m.

def modular_sum(arr, n, m):
	if (n > m):
		return True
	DP = [False for i in range(m)]
	for i in range(n):
		if (DP[0]):
			return True
		temp = [False for i in range(m)]
		for j in range(m):
			if (DP[j] == True):
				if (DP[(j + arr[i]) % m] == False):
					temp[(j + arr[i]) % m] = True
		for j in range(m):
			if (temp[j]):
				DP[j] = True
		DP[arr[i] % m] = True
	return DP[0]

assert modular_sum([3, 1, 7, 5], 4, 6) == True

assert modular_sum([1, 7], 2, 5) == False

assert modular_sum([1, 6], 2, 5) == False


Write a function to sort a list of elements using radix sort.

def radix_sort(nums):
    RADIX = 10
    placement = 1
    max_digit = max(nums)

    while placement < max_digit:
      buckets = [list() for _ in range( RADIX )]
      for i in nums:
        tmp = int((i / placement) % RADIX)
        buckets[tmp].append(i)
      a = 0
      for b in range( RADIX ):
        buck = buckets[b]
        for i in buck:
          nums[a] = i
          a += 1
      placement *= RADIX
    return nums


Write a python function to find the largest postive number from the given list.

def largest_pos(list1):
    max = list1[0]
    for x in list1:
        if x > max :
             max = x
    return max


Write a function to find the square root of a perfect number.

import math
def sqrt_root(num):
 sqrt_root = math.pow(num, 0.5)
 return sqrt_root

assert sqrt_root(4)==2
assert sqrt_root(16)==4
assert sqrt_root(400)==20


Write a function to calculate volume of a tetrahedron.

import math
def volume_tetrahedron(num):
	volume = (num ** 3 / (6 * math.sqrt(2)))
	return round(volume, 2)

assert volume_tetrahedron(10)==117.85
assert volume_tetrahedron(15)==397.75
assert volume_tetrahedron(20)==942.81


Write a function to find the lcm of the given array elements.

def find_lcm(num1, num2):
	if(num1>num2):
		num = num1
		den = num2
	else:
		num = num2
		den = num1
	rem = num % den
	while (rem != 0):
		num = den
		den = rem
		rem = num % den
	gcd = den
	lcm = int(int(num1 * num2)/int(gcd))
	return lcm
def get_lcm(l):
  num1 = l[0]
  num2 = l[1]
  lcm = find_lcm(num1, num2)
  for i in range(2, len(l)):
    lcm = find_lcm(lcm, l[i])
  return lcm


Write a function to print check if the triangle is scalene or not.

def check_isosceles(x,y,z):
  if x!=y & y!=z & z!=x:
	   return True
  else:
     return False

assert check_isosceles(6,8,12)==True
assert check_isosceles(6,6,12)==False
assert check_isosceles(6,15,20)==True


Write a function to find the longest bitonic subsequence for the given array.

def lbs(arr):
	n = len(arr)
	lis = [1 for i in range(n+1)]
	for i in range(1 , n):
		for j in range(0 , i):
			if ((arr[i] > arr[j]) and (lis[i] < lis[j] +1)):
				lis[i] = lis[j] + 1
	lds = [1 for i in range(n+1)]
	for i in reversed(range(n-1)):
		for j in reversed(range(i-1 ,n)):
			if(arr[i] > arr[j] and lds[i] < lds[j] + 1):
				lds[i] = lds[j] + 1
	maximum = lis[0] + lds[0] - 1
	for i in range(1 , n):
		maximum = max((lis[i] + lds[i]-1), maximum)
	return maximum


Write a function to check whether a given string has a capital letter, a lower case letter, a number and specified length using lambda function.

def check_string(str1):
    messg = [
    lambda str1: any(x.isupper() for x in str1) or 'String must have 1 upper case character.',
    lambda str1: any(x.islower() for x in str1) or 'String must have 1 lower case character.',
    lambda str1: any(x.isdigit() for x in str1) or 'String must have 1 number.',
    lambda str1: len(str1) >= 7                 or 'String length should be atleast 8.',]
    result = [x for x in [i(str1) for i in messg] if x != True]
    if not result:
        result.append('Valid string.')
    return result

assert check_string('python')==['String must have 1 upper case character.', 'String must have 1 number.', 'String length should be atleast 8.']

assert check_string('123python')==['String must have 1 upper case character.']


Write a function to find the sum of maximum increasing subsequence of the given array.

def max_sum_increasing_subsequence(arr, n):
	max = 0
	msis = [0 for x in range(n)]
	for i in range(n):
		msis[i] = arr[i]
	for i in range(1, n):
		for j in range(i):
			if (arr[i] > arr[j] and
				msis[i] < msis[j] + arr[i]):
				msis[i] = msis[j] + arr[i]
	for i in range(n):
		if max < msis[i]:
			max = msis[i]
	return max

assert max_sum_increasing_subsequence([1, 101, 2, 3, 100, 4, 5], 7) == 106

assert max_sum_increasing_subsequence([3, 4, 5, 10], 4) == 22

assert max_sum_increasing_subsequence([10, 5, 4, 3], 4) == 10


Write a python function to check whether two given lines are parallel or not.

def parallel_lines(line1, line2):
  return line1[0]/line1[1] == line2[0]/line2[1]

assert parallel_lines([2,3,4], [2,3,8]) == True

assert parallel_lines([2,3,4], [4,-3,8]) == False

assert parallel_lines([3,3],[5,5]) == True


Write a python function to capitalize first and last letters of each word of a given string.

def capitalize_first_last_letters(str1):
     str1 = result = str1.title()
     result =  ""
     for word in str1.split():
        result += word[:-1] + word[-1].upper() + " "
     return result[:-1]

assert capitalize_first_last_letters("python") == "PythoN"

assert capitalize_first_last_letters("bigdata") == "BigdatA"

assert capitalize_first_last_letters("Hadoop") == "HadooP"


Write a function to find all pairs in an integer array whose sum is equal to a given number.

def get_pairs_count(arr, n, sum):
    count = 0
    for i in range(0, n):
        for j in range(i + 1, n):
            if arr[i] + arr[j] == sum:
                count += 1
    return count


Write a function to find the list of lists with minimum length.

def min_length(list1):
   min_length = min(len(x) for x in  list1 )
   min_list = min((x) for x in   list1)
   return(min_length, min_list)


Write a function to find the nth jacobsthal-lucas number.

def jacobsthal_lucas(n):
	dp=[0] * (n + 1)
	dp[0] = 2
	dp[1] = 1
	for i in range(2, n+1):
		dp[i] = dp[i - 1] + 2 * dp[i - 2];
	return dp[n]

assert jacobsthal_lucas(5) == 31
assert jacobsthal_lucas(2) == 5
assert jacobsthal_lucas(4) == 17


Write a function to find the ration of negative numbers in an array of integers.

from array import array
def negative_count(nums):
    n = len(nums)
    n1 = 0
    for x in nums:
        if x < 0:
            n1 += 1
        else:
          None
    return round(n1/n,2)


Write a function to find minimum number of coins that make a given value.

import sys
def min_coins(coins, m, V):
    if (V == 0):
        return 0
    res = sys.maxsize
    for i in range(0, m):
        if (coins[i] <= V):
            sub_res = min_coins(coins, m, V-coins[i])
            if (sub_res != sys.maxsize and sub_res + 1 < res):
                res = sub_res + 1
    return res


Write a function to check if the two given strings are permutations of each other.

def check_permutation(str1, str2):
  n1=len(str1)
  n2=len(str2)
  if(n1!=n2):
    return False
  a=sorted(str1)
  str1=" ".join(a)
  b=sorted(str2)
  str2=" ".join(b)
  for i in range(0, n1, 1):
    if(str1[i] != str2[i]):
      return False
  return True

assert check_permutation("abc", "cba") == True

assert check_permutation("test", "ttew") == False

assert check_permutation("xxyz", "yxzx") == True


Write a function to remove particular data type elements from the given tuple.

def remove_datatype(test_tuple, data_type):
  res = []
  for ele in test_tuple:
    if not isinstance(ele, data_type):
      res.append(ele)
  return (res)

assert remove_datatype((7, 8, 9, "SR"), str) == [7, 8, 9]

assert remove_datatype((7, 1.1, 2, 2.2), float) == [7, 2]


Write a function to search a literals string in a string and also find the location within the original string where the pattern occurs.

import re
def search_literal(pattern,text):
 match = re.search(pattern, text)
 s = match.start()
 e = match.end()
 return (s, e)

assert search_literal('python','python programming language')==(0,6)

assert search_literal('programming','python programming language')==(7,18)

assert search_literal('language','python programming language')==(19,27)


Write a function to find the top or bottom surface area of a cylinder.

def topbottom_surfacearea(r):
  toporbottomarea=3.1415*r*r
  return toporbottomarea


Write a function to select the nth items of a list.

def nth_items(list,n):
 return list[::n]


Write a python function to find the first repeated word in a given string.

def first_repeated_word(str1):
  temp = set()
  for word in str1.split():
    if word in temp:
      return word;
    else:
      temp.add(word)
  return 'None'

assert first_repeated_word("ab ca bc ab") == "ab"

assert first_repeated_word("ab ca bc") == 'None'

assert first_repeated_word("ab ca bc ca ab bc") == "ca"


Write a python function to convert a given string list to a tuple.

def string_list_to_tuple(str1):
    result = tuple(x for x in str1 if not x.isspace())
    return result

assert string_list_to_tuple(("bigdata")) == ('b', 'i', 'g', 'd', 'a', 't', 'a')

assert string_list_to_tuple(("language")) == ('l', 'a', 'n', 'g', 'u', 'a', 'g','e')


Write a function to create a list containing the power of said number in bases raised to the corresponding number in the index using map function.

def basesnum_coresspondingnum(bases_num,index):
  result = list(map(pow, bases_num, index))
  return result


Write a python function to find the difference between highest and least frequencies in a given array.

def find_Diff(arr,n):
    arr.sort()
    count = 0; max_count = 0; min_count = n
    for i in range(0,(n-1)):
        if arr[i] == arr[i + 1]:
            count += 1
            continue
        else:
            max_count = max(max_count,count)
            min_count = min(min_count,count)
            count = 0
    return max_count - min_count


Write a function to find if the given number is abundant or not.

import math
def get_sum(n):
	sum = 0
	i = 1
	while i <= (math.sqrt(n)):
		if n%i == 0:
			if n/i == i :
				sum = sum + i
			else:
				sum = sum + i
				sum = sum + (n / i )
		i = i + 1
	sum = sum - n
	return sum
def check_abundant(n):
	if (get_sum(n) > n):
		return True
	else:
		return False

assert check_abundant(12) == True
assert check_abundant(15) == False
assert check_abundant(18) == True


Write a function to replace all occurrences of spaces, commas, or dots with a colon in the given string by using regex.

import re
def fill_spaces(text):
  return (re.sub("[ ,.]", ":", text))

assert fill_spaces('Boult Curve Wireless Neckband') == 'Boult:Curve:Wireless:Neckband'

assert fill_spaces('Stereo Sound Sweatproof') == 'Stereo:Sound:Sweatproof'

assert fill_spaces('Probass Curve Audio') == 'Probass:Curve:Audio'


Write a function to add two numbers and print number of digits of sum.

def count_digits(num1,num2):
    number=num1+num2
    count = 0
    while(number > 0):
        number = number // 10
        count = count + 1
    return count


Write a function to flatten the tuple list to a string.

def flatten_tuple(test_list):
  res = ' '.join([idx for tup in test_list for idx in tup])
  return (res)


Write a python function to toggle only first and last bits of a given number.

def take_L_and_F_set_bits(n) :
    n = n | n >> 1
    n = n | n >> 2
    n = n | n >> 4
    n = n | n >> 8
    n = n | n >> 16
    return ((n + 1) >> 1) + 1
def toggle_F_and_L_bits(n) :
    if (n == 1) :
        return 0
    return n ^ take_L_and_F_set_bits(n)

assert toggle_F_and_L_bits(10) == 3
assert toggle_F_and_L_bits(15) == 6
assert toggle_F_and_L_bits(20) == 5


Write a function to find the last occurrence of a character in a string.

def last_occurence_char(string,char):
 flag = -1
 for i in range(len(string)):
     if(string[i] == char):
         flag = i
 if(flag == -1):
    return None
 else:
    return flag + 1


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

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 function to find the length of the longest increasing subsequence of the given sequence.

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 python function to find the sum of fifth power of first n odd natural numbers.

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 maximum element in a sorted and rotated array.

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 function to extract a specified column from a given nested list.

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


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

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 function to convert the given tuple to a floating-point number.

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 python function to find odd numbers from a mixed list.

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 the difference between sum of cubes of first n natural numbers and the sum of first n natural numbers.

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 count the pairs with xor as an odd number.

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 function to toggle characters case in a string.

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


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

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

assert digit_distance_nums(123,256) == 7


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

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 union of elements of the given tuples.

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


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

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 python function to find the maximum length of sublist.

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


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

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

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


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

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 split a string into characters.

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

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


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

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 check whether a specified list is sorted or not.

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


Write a function to create a list of empty dictionaries.

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


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

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 remove words from a given list of strings containing a character or string.

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 find maximum possible sum of disjoint pairs for the given array of integers and a number k.

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 python function to remove two duplicate numbers from a given number of lists.

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


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

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 function to find the surface area of a cylinder.

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


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

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 check whether an array is subarray of another or not.

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 find the last digit in factorial of a given number.

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 function to interleave lists of the same length.

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 find the dissimilar elements in the given two tuples.

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


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

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 python function to find the surface area of the square pyramid.

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 function to check if a dictionary is empty or not.

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 for nth catalan number.

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 to find all adverbs and their positions in a given sentence by using regex.

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 the n - expensive price items from a given dataset using heap queue algorithm.

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


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

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


Write a function to convert a list to a tuple.

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


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

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


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

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 convert polar coordinates to rectangular coordinates.

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 python function to interchange the first and last elements in a list.

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 find sum of product of binomial co-efficients.

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 function to remove leading zeroes from an ip address.

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


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

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 python function to count minimum number of swaps required to convert one binary string to another.

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 function to find the size of the given tuple.

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 kth element from the given two sorted arrays.

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]