class Pair(object):
	def __init__(self, a, b):
		self.a = a
		self.b = b
def max_chain_length(arr, n):
	max = 0
	mcl = [1 for i in range(n)]
	for i in range(1, n):
		for j in range(0, i):
			if (arr[i].a > arr[j].b and
				mcl[i] < mcl[j] + 1):
				mcl[i] = mcl[j] + 1
	for i in range(n):
		if (max < mcl[i]):
			max = mcl[i]
	return max

assert max_chain_length([Pair(1, 2), Pair(3, 4),Pair(5, 6), Pair(7, 8)], 4) == 4

Write a function to find the longest chain which can be formed from the given set of pairs.


def first_repeated_char(str1):
  for index,c in enumerate(str1):
    if str1[:index+1].count(c) > 1:
      return c
  return "None"

assert first_repeated_char("abcabc") == "a"

assert first_repeated_char("abc") == "None"

assert first_repeated_char("123123") == "1"

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


def get_ludic(n):
	ludics = []
	for i in range(1, n + 1):
		ludics.append(i)
	index = 1
	while(index != len(ludics)):
		first_ludic = ludics[index]
		remove_index = index + first_ludic
		while(remove_index < len(ludics)):
			ludics.remove(ludics[remove_index])
			remove_index = remove_index + first_ludic - 1
		index += 1
	return ludics

Write a function to get a lucid number smaller than or equal to n.


def reverse_words(s):
        return ' '.join(reversed(s.split()))

assert reverse_words("python program")==("program python")

assert reverse_words("java language")==("language java")

assert reverse_words("indian man")==("man indian")

Write a function to reverse words in a given string.


def prime_num(num):
  if num >=1:
   for i in range(2, num//2):
     if (num % i) == 0:
                return False
     else:
                return True
  else:
          return False

assert prime_num(13)==True
assert prime_num(7)==True
assert prime_num(-1010)==False

Write a function to check if the given integer is a prime number.


import math
def radian_degree(degree):
 radian = degree*(math.pi/180)
 return radian

Write a function to convert degrees to radians.


import re
pattern = 'fox'
text = 'The quick brown fox jumps over the lazy dog.'
def find_literals(text, pattern):
  match = re.search(pattern, text)
  s = match.start()
  e = match.end()
  return (match.re.pattern, s, e)

assert find_literals('The quick brown fox jumps over the lazy dog.', 'fox') == ('fox', 16, 19)

assert find_literals('Its been a very crazy procedure right', 'crazy') == ('crazy', 16, 21)

assert find_literals('Hardest choices required strongest will', 'will') == ('will', 35, 39)

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


def bell_Number(n):
    bell = [[0 for i in range(n+1)] for j in range(n+1)]
    bell[0][0] = 1
    for i in range(1, n+1):
        bell[i][0] = bell[i-1][i-1]
        for j in range(1, i+1):
            bell[i][j] = bell[i-1][j-1] + bell[i][j-1]
    return bell[n][0]

assert bell_Number(2) == 2
assert bell_Number(3) == 5
assert bell_Number(4) == 15

Write a python function to find nth bell number.


def floor_Min(A,B,N):
    x = max(B - 1,N)
    return (A*x) // B

assert floor_Min(10,20,30) == 15
assert floor_Min(1,2,1) == 0
assert floor_Min(11,10,9) == 9

Write a python function to find minimum possible value for the given periodic function.


def remove_kth_element(list1, L):
    return  list1[:L-1] + list1[L:]

Write a python function to remove the k'th element from a given list.


def max_of_nth(test_list, N):
  res = max([sub[N] for sub in test_list])
  return (res)

Write a function to find the maximum of nth column from the given tuple list.


def merge(lst):
    return [list(ele) for ele in list(zip(*lst))]

Write a python function to merge the first and last elements separately in a list of lists.


def maximum_value(test_list):
  res = [(key, max(lst)) for key, lst in test_list]
  return (res)

Write a function to find the maximum value in record list as tuple attribute in the given tuple list.


def cummulative_sum(test_list):
  res = sum(map(sum, test_list))
  return (res)

Write a function to find the cumulative sum of all the values that are present in the given tuple list.


def average_tuple(nums):
    result = [sum(x) / len(x) for x in zip(*nums)]
    return result

Write a function to find average value of the numbers in a given tuple of tuples.


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

Write a function to perfom the modulo of tuple elements in the given two tuples.


def min_Jumps(a, b, d):
    temp = a
    a = min(a, b)
    b = max(temp, b)
    if (d >= b):
        return (d + b - 1) / b
    if (d == 0):
        return 0
    if (d == a):
        return 1
    else:
        return 2

assert min_Jumps(3,4,11)==3.5
assert min_Jumps(3,4,0)==0
assert min_Jumps(11,14,11)==1

Write a function to check for the number of jumps required of given length to reach a point of form (d, 0) from origin in a 2d plane.


def div_list(nums1,nums2):
  result = map(lambda x, y: x / y, nums1, nums2)
  return list(result)

Write a function to divide two lists using map and lambda function.


def move_num(test_str):
  res = ''
  dig = ''
  for ele in test_str:
    if ele.isdigit():
      dig += ele
    else:
      res += ele
  res += dig
  return (res)

assert move_num('I1love143you55three3000thousand') == 'Iloveyouthreethousand1143553000'

assert move_num('Avengers124Assemble') == 'AvengersAssemble124'

assert move_num('Its11our12path13to14see15things16do17things') == 'Itsourpathtoseethingsdothings11121314151617'

Write a function to move all the numbers in it to the given string.


def largest_subset(a, n):
	dp = [0 for i in range(n)]
	dp[n - 1] = 1;
	for i in range(n - 2, -1, -1):
		mxm = 0;
		for j in range(i + 1, n):
			if a[j] % a[i] == 0 or a[i] % a[j] == 0:
				mxm = max(mxm, dp[j])
		dp[i] = 1 + mxm
	return max(dp)

Write a function to find the largest subset where each pair is divisible.


def increment_numerics(test_list, K):
  res = [str(int(ele) + K) if ele.isdigit() else ele for ele in test_list]
  return res

Write a function to increment the numeric values in the given strings by k.


def get_median(arr1, arr2, n):
  i = 0
  j = 0
  m1 = -1
  m2 = -1
  count = 0
  while count < n + 1:
    count += 1
    if i == n:
      m1 = m2
      m2 = arr2[0]
      break
    elif j == n:
      m1 = m2
      m2 = arr1[0]
      break
    if arr1[i] <= arr2[j]:
      m1 = m2
      m2 = arr1[i]
      i += 1
    else:
      m1 = m2
      m2 = arr2[j]
      j += 1
  return (m1 + m2)/2

Write a function to find the median of two sorted arrays of same size.


def nth_nums(nums,n):
 nth_nums = list(map(lambda x: x ** n, nums))
 return nth_nums

Write a function to find the n-th power of individual elements in a list using lambda function.


def is_upper(string):
  return (string.upper())

assert is_upper("person") =="PERSON"
assert is_upper("final") == "FINAL"
assert is_upper("Valid") == "VALID"

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


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

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


def triangle_area(r) :
    if r < 0 :
        return -1
    return r * r

assert triangle_area(0) == 0
assert triangle_area(-1) == -1
assert triangle_area(2) == 4

Write a python function to find the largest triangle that can be inscribed in the semicircle.


def find_First_Missing(array,start,end):
    if (start > end):
        return end + 1
    if (start != array[start]):
        return start;
    mid = int((start + end) / 2)
    if (array[mid] == mid):
        return find_First_Missing(array,mid+1,end)
    return find_First_Missing(array,start,mid)

assert find_First_Missing([0,1,2,3],0,3) == 4

assert find_First_Missing([0,1,2,6,9],0,4) == 3

assert find_First_Missing([2,3,5,8,9],0,4) == 0

Write a python function to find the smallest missing number from the given array.


MAX=1000;
def replace_spaces(string):
  string=string.strip()
  i=len(string)
  space_count=string.count(' ')
  new_length = i + space_count*2
  if new_length > MAX:
    return -1
  index = new_length-1
  string=list(string)
  for f in range(i-2, new_length-2):
    string.append('0')
  for j in range(i-1, 0, -1):
    if string[j] == ' ':
      string[index] = '0'
      string[index-1] = '2'
      string[index-2] = '%'
      index=index-3
    else:
      string[index] = string[j]
      index -= 1
  return ''.join(string)

assert replace_spaces("My Name is Dawood") == 'My%20Name%20is%20Dawood'

assert replace_spaces("I am a Programmer") == 'I%20am%20a%20Programmer'

assert replace_spaces("I love Coding") == 'I%20love%20Coding'

Write a function to replace all spaces in the given string with character * list item * list item * list item * list item '%20'.


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

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


def adjac(ele, sub = []):
  if not ele:
     yield sub
  else:
     yield from [idx for j in range(ele[0] - 1, ele[0] + 2)
                for idx in adjac(ele[1:], sub + [j])]
def get_coordinates(test_tup):
  res = list(adjac(test_tup))
  return (res)

Write a function to extract all the adjacent coordinates of the given coordinate tuple.


import re
text = 'Python Exercises'
def replace_spaces(text):
  text =text.replace (" ", "_")
  return (text)
  text =text.replace ("_", " ")
  return (text)

assert replace_spaces('Jumanji The Jungle') == 'Jumanji_The_Jungle'

assert replace_spaces('The Avengers') == 'The_Avengers'

assert replace_spaces('Fast and Furious') == 'Fast_and_Furious'

Write a function to replace whitespaces with an underscore and vice versa in a given string by using regex.


def move_zero(num_list):
    a = [0 for i in range(num_list.count(0))]
    x = [ i for i in num_list if i != 0]
    x.extend(a)
    return (x)

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


def pair_OR_Sum(arr,n) :
    ans = 0
    for i in range(0,n) :
        for j in range(i + 1,n) :
            ans = ans + (arr[i] ^ arr[j])
    return ans

Write a python function to find the sum of xor of all pairs of numbers in the given array.


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

assert even_Power_Sum(2) == 272
assert even_Power_Sum(3) == 1568
assert even_Power_Sum(4) == 5664

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


import heapq as hq
def heap_sort(iterable):
    h = []
    for value in iterable:
        hq.heappush(h, value)
    return [hq.heappop(h) for i in range(len(h))]

Write a function to push all values into a heap and then pop off the smallest values one at a time.


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

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

Write a python function to check if roots of a quadratic equation are reciprocal of each other or not.


def noprofit_noloss(actual_cost,sale_amount):
  if(sale_amount == actual_cost):
    return True
  else:
    return False

Write a function to check whether the given amount has no profit and no loss


import math
def wind_chill(v,t):
 windchill = 13.12 + 0.6215*t -  11.37*math.pow(v, 0.16) + 0.3965*t*math.pow(v, 0.16)
 return int(round(windchill, 0))

assert wind_chill(120,35)==40
assert wind_chill(40,70)==86
assert wind_chill(10,100)==116

Write a function to calculate wind chill index.


def sample_nam(sample_names):
  sample_names=list(filter(lambda el:el[0].isupper() and el[1:].islower(),sample_names))
  return len(''.join(sample_names))

assert sample_nam(['sally', 'Dylan', 'rebecca', 'Diana', 'Joanne', 'keith'])==16

assert sample_nam(["php", "res", "Python", "abcd", "Java", "aaa"])==10

assert sample_nam(["abcd", "Python", "abba", "aba"])==6

Write a function to sum the length of the names of a given list of names after removing the names that start with a lowercase letter.


import re
def remove_parenthesis(items):
 for item in items:
    return (re.sub(r" ?\([^)]+\)", "", item))

Write a function to remove the parenthesis area in a string.


def is_nonagonal(n):
	return int(n * (7 * n - 5) / 2)

assert is_nonagonal(10) == 325
assert is_nonagonal(15) == 750
assert is_nonagonal(18) == 1089

Write a function to find the nth nonagonal number.


def remove_similar_row(test_list):
  res = set(sorted([tuple(sorted(set(sub))) for sub in test_list]))
  return (res)

Write a function to remove similar rows from the given tuple matrix.


import re
def text_match_wordz_middle(text):
        patterns = '\Bz\B'
        if re.search(patterns,  text):
                return 'Found a match!'
        else:
                return('Not matched!')

assert text_match_wordz_middle("pythonzabc.")==('Found a match!')

assert text_match_wordz_middle("xyzabc.")==('Found a match!')

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

Write a function that matches a word containing 'z', not at the start or end of the word.


def reverse_Array_Upto_K(input, k):
  return (input[k-1::-1] + input[k:])

Write a python function to reverse an array upto a given position.


def get_product(val) :
	res = 1
	for ele in val:
		res *= ele
	return res
def find_k_product(test_list, K):
  res = get_product([sub[K] for sub in test_list])
  return (res)

Write a function to find the product of it’s kth index in the given tuples.


def No_of_cubes(N,K):
    No = 0
    No = (N - K + 1)
    No = pow(No, 3)
    return No

assert No_of_cubes(2,1) == 8
assert No_of_cubes(5,2) == 64
assert No_of_cubes(1,1) == 1

Write a python function to count number of cubes of size k in a cube of size n.


import re
def split_upperstring(text):
 return (re.findall('[A-Z][^A-Z]*', text))

Write a function to split a string at uppercase letters.


from itertools import zip_longest, chain, tee
def exchange_elements(lst):
    lst1, lst2 = tee(iter(lst), 2)
    return list(chain.from_iterable(zip_longest(lst[1::2], lst[::2])))

Write a function to exchange the position of every n-th value with (n+1)th value and (n+1)th value with n-th value in a given list.


def sum_Range_list(nums, m, n):
    sum_range = 0
    for i in range(m, n+1, 1):
        sum_range += nums[i]
    return sum_range

Write a python function to calculate the sum of the numbers in a list between the indices of a specified range.


def are_Equal(arr1,arr2,n,m):
    if (n != m):
        return False
    arr1.sort()
    arr2.sort()
    for i in range(0,n - 1):
        if (arr1[i] != arr2[i]):
            return False
    return True

Write a python function to check whether the given two arrays are equal or not.


def check_subset(test_tup1, test_tup2):
  res = set(test_tup2).issubset(test_tup1)
  return (res)

assert check_subset((1, 2, 3, 4), (5, 6)) == False

Write a function to check if one tuple is a subset of another tuple.


def matrix_to_list(test_list):
  temp = [ele for sub in test_list for ele in sub]
  res = list(zip(*temp))
  return (str(res))

Write a function to flatten the given tuple matrix into the tuple list with each tuple representing each column.


from collections import defaultdict
def grouping_dictionary(l):
    d = defaultdict(list)
    for k, v in l:
        d[k].append(v)
    return d

Write a function to group a sequence of key-value pairs into a dictionary of lists using collections module.


def rectangle_perimeter(l,b):
  perimeter=2*(l+b)
  return perimeter

assert rectangle_perimeter(10,20)==60
assert rectangle_perimeter(10,5)==30
assert rectangle_perimeter(4,2)==12

Write a function to find the perimeter of a rectangle.


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

assert fifth_Power_Sum(2) == 33
assert fifth_Power_Sum(4) == 1300
assert fifth_Power_Sum(3) == 276

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


def find_Min_Sum(a,b,n):
    a.sort()
    b.sort()
    sum = 0
    for i in range(n):
        sum = sum + abs(a[i] - b[i])
    return sum

Write a python function to find the minimum sum of absolute differences of two arrays.


import math
def first_Digit(n) :
    fact = 1
    for i in range(2,n + 1) :
        fact = fact * i
        while (fact % 10 == 0) :
            fact = int(fact / 10)
    while (fact >= 10) :
        fact = int(fact / 10)
    return math.floor(fact)

assert first_Digit(5) == 1
assert first_Digit(10) == 3
assert first_Digit(7) == 5

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


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

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


def Repeat(x):
    _size = len(x)
    repeated = []
    for i in range(_size):
        k = i + 1
        for j in range(k, _size):
            if x[i] == x[j] and x[i] not in repeated:
                repeated.append(x[i])
    return repeated

Write a python function to print duplicants from a list of integers.


def find_Points(l1,r1,l2,r2):
    x = min(l1,l2) if (l1 != l2) else -1
    y = max(r1,r2) if (r1 != r2) else -1
    return (x,y)

Write a python function to choose points from two ranges such that no point lies in both the ranges.


def max_sum_of_three_consecutive(arr, n):
	sum = [0 for k in range(n)]
	if n >= 1:
		sum[0] = arr[0]
	if n >= 2:
		sum[1] = arr[0] + arr[1]
	if n > 2:
		sum[2] = max(sum[1], max(arr[1] + arr[2], arr[0] + arr[2]))
	for i in range(3, n):
		sum[i] = max(max(sum[i-1], sum[i-2] + arr[i]), arr[i] + arr[i-1] + sum[i-3])
	return sum[n-1]

assert max_sum_of_three_consecutive([1, 2, 3, 4, 5, 6, 7, 8], 8) == 27

Write a function to find the maximum sum that can be formed which has no three consecutive elements present.


def sorted_dict(dict1):
  sorted_dict = {x: sorted(y) for x, y in dict1.items()}
  return sorted_dict

Write a function to sort a list in a dictionary.


import sys
def find_max_val(n, x, y):
	ans = -sys.maxsize
	for k in range(n + 1):
		if (k % x == y):
			ans = max(ans, k)
	return (ans if (ans >= 0 and
					ans <= n) else -1)

assert find_max_val(15, 10, 5) == 15
assert find_max_val(187, 10, 5) == 185
assert find_max_val(16, 11, 1) == 12

Write a function to find the largest possible value of k such that k modulo x is y.


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

assert average_Even(2) == 2
assert average_Even(4) == 3
assert average_Even(100) == 51

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


def move_last(num_list):
    a = [num_list[0] for i in range(num_list.count(num_list[0]))]
    x = [ i for i in num_list if i != num_list[0]]
    x.extend(a)
    return (x)

Write a python function to shift first element to the end of given list.


def count_char(string,char):
 count = 0
 for i in range(len(string)):
    if(string[i] == char):
        count = count + 1
 return count

assert count_char("Python",'o')==1
assert count_char("little",'t')==2
assert count_char("assert",'s')==2

Write a function to count occurrence of a character in a string.


def Check_Vow(string, vowels):
    final = [each for each in string if each in vowels]
    return(len(final))

assert Check_Vow('corner','AaEeIiOoUu') == 2

assert Check_Vow('valid','AaEeIiOoUu') == 2

Write a python function to count number of vowels in the string.


import re
def replace(string, char):
    pattern = char + '{2,}'
    string = re.sub(pattern, char, string)
    return string

assert replace('peep','e') == 'pep'
assert replace('Greek','e') == 'Grek'
assert replace('Moon','o') == 'Mon'

Write a python function to replace multiple occurence of character by single.


assert check_IP("192.168.0.1") == 'Valid IP address'

assert check_IP("110.234.52.124") == 'Valid IP address'

assert check_IP("366.1.2.2") == 'Invalid IP address'

Write a function to check whether the given ip address is valid or not using regex.


def decreasing_trend(nums):
    if (sorted(nums)== nums):
        return True
    else:
        return False

assert decreasing_trend([-4,-3,-2,-1]) == True

assert decreasing_trend([1,2,3]) == True

assert decreasing_trend([3,2,1]) == False

Write a python function to check whether a sequence of numbers has a decreasing trend or not.


import math
def get_Pos_Of_Right_most_Set_Bit(n):
    return int(math.log2(n&-n)+1)
def set_Right_most_Unset_Bit(n):
    if (n == 0):
        return 1
    if ((n & (n + 1)) == 0):
        return n
    pos = get_Pos_Of_Right_most_Set_Bit(~n)
    return ((1 << (pos - 1)) | n)

assert set_Right_most_Unset_Bit(21) == 23

assert set_Right_most_Unset_Bit(11) == 15

assert set_Right_most_Unset_Bit(15) == 15

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


def max_of_three(num1,num2,num3):
    if (num1 >= num2) and (num1 >= num3):
       lnum = num1
    elif (num2 >= num1) and (num2 >= num3):
       lnum = num2
    else:
       lnum = num3
    return lnum

assert max_of_three(10,20,30)==30
assert max_of_three(55,47,39)==55
assert max_of_three(10,49,30)==49

Write a function to find maximum of three numbers.


def convert(list):
    s = [str(i) for i in list]
    res = int("".join(s))
    return (res)

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


from collections import OrderedDict
def remove_duplicate(string):
  result = ' '.join(OrderedDict((w,w) for w in string.split()).keys())
  return result

assert remove_duplicate("Python Exercises Practice Solution Exercises")==("Python Exercises Practice Solution")

assert remove_duplicate("Python Exercises Practice Solution Python")==("Python Exercises Practice Solution")

assert remove_duplicate("Python Exercises Practice Solution Practice")==("Python Exercises Practice Solution")

Write a function to remove duplicate words from a given string using collections module.


def sum_nums(x, y,m,n):
    sum_nums= x + y
    if sum_nums in range(m, n):
        return 20
    else:
        return sum_nums

Write a function to add two integers. however, if the sum is between the given range it will return 20.


import re
def remove_extra_char(text1):
  pattern = re.compile('[\W_]+')
  return (pattern.sub('', text1))

assert remove_extra_char('**//Google Android// - 12. ') == 'GoogleAndroid12'

assert remove_extra_char('****//Google Flutter//*** - 36. ') == 'GoogleFlutter36'

assert remove_extra_char('**//Google Firebase// - 478. ') == 'GoogleFirebase478'

Write a function to remove everything except alphanumeric characters from the given string by using regex.


def validity_triangle(a,b,c):
 total = a + b + c
 if total == 180:
    return True
 else:
    return False

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


def remove_spaces(str1):
  str1 = str1.replace(' ','')
  return str1

assert remove_spaces("a b c") == "abc"
assert remove_spaces("1 2 3") == "123"
assert remove_spaces(" b c") == "bc"

Write a python function to remove spaces from a given string.


def access_key(ditionary,key):
  return list(ditionary)[key]

assert access_key({'physics': 80, 'math': 90, 'chemistry': 86},0)== 'physics'

Write a function to access dictionary key’s element by index.


def increasing_trend(nums):
    if (sorted(nums)== nums):
        return True
    else:
        return False

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

assert increasing_trend([4,3,2,1]) == False

assert increasing_trend([0,1,4,9]) == True

Write a python function to check whether a sequence of numbers has an increasing trend or not.


def smallest_Divisor(n):
    if (n % 2 == 0):
        return 2;
    i = 3;
    while (i*i <= n):
        if (n % i == 0):
            return i;
        i += 2;
    return n;

assert smallest_Divisor(10) == 2
assert smallest_Divisor(25) == 5
assert smallest_Divisor(31) == 31

Write a python function to find the smallest prime divisor of a number.


def mul_list(nums1,nums2):
  result = map(lambda x, y: x * y, nums1, nums2)
  return list(result)

Write a function to multiply two lists using map and lambda function.


def sum_Square(n) :
    i = 1
    while i*i <= n :
        j = 1
        while (j*j <= n) :
            if (i*i+j*j == n) :
                return True
            j = j+1
        i = i+1
    return False

assert sum_Square(25) == True
assert sum_Square(24) == False
assert sum_Square(17) == True

Write a python function to check whether the given number can be represented by sum of two squares or not.


def count_Char(str,x):
    count = 0
    for i in range(len(str)):
        if (str[i] == x) :
            count += 1
    n = 10
    repititions = n // len(str)
    count = count * repititions
    l = n % len(str)
    for i in range(l):
        if (str[i] == x):
            count += 1
    return count

assert count_Char("abcac",'a') == 4
assert count_Char("abca",'c') == 2
assert count_Char("aba",'a') == 7

Write a python function to count occurences of a character in a repeated string.


def sum_Of_Primes(n):
    prime = [True] * (n + 1)
    p = 2
    while p * p <= n:
        if prime[p] == True:
            i = p * 2
            while i <= n:
                prime[i] = False
                i += p
        p += 1
    sum = 0
    for i in range (2,n + 1):
        if(prime[i]):
            sum += i
    return sum

assert sum_Of_Primes(10) == 17
assert sum_Of_Primes(20) == 77
assert sum_Of_Primes(5) == 10

Write a python function to find sum of prime numbers between 1 to n.


from collections import defaultdict
def freq_element(test_tup):
  res = defaultdict(int)
  for ele in test_tup:
    res[ele] += 1
  return (str(dict(res)))

Write a function to find the frequency of each element in the given list.


def recur_gcd(a, b):
	low = min(a, b)
	high = max(a, b)
	if low == 0:
		return high
	elif low == 1:
		return 1
	else:
		return recur_gcd(low, high%low)

assert recur_gcd(12,14) == 2
assert recur_gcd(13,17) == 1
assert recur_gcd(9, 3) == 3

Write a function to find the greatest common divisor (gcd) of two integers by using recursion.


import cmath
def len_complex(a,b):
  cn=complex(a,b)
  length=abs(cn)
  return length

Write a function to get the length of a complex number.


def min_jumps(arr, n):
	jumps = [0 for i in range(n)]
	if (n == 0) or (arr[0] == 0):
		return float('inf')
	jumps[0] = 0
	for i in range(1, n):
		jumps[i] = float('inf')
		for j in range(i):
			if (i <= j + arr[j]) and (jumps[j] != float('inf')):
				jumps[i] = min(jumps[i], jumps[j] + 1)
				break
	return jumps[n-1]

## write a function to find the minimum number of jumps to reach the end of the array for the given array of integers where each element represents the max number of steps that can be made forward from that element. > indented block > indented block


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

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


from itertools import groupby
def group_element(test_list):
  res = dict()
  for key, val in groupby(sorted(test_list, key = lambda ele: ele[1]), key = lambda ele: ele[1]):
    res[key] = [ele[0] for ele in val]
  return (res)

Write a function to group the 1st elements on the basis of 2nd elements in the given tuple list.


def last_Two_Digits(N):
    if (N >= 10):
        return
    fac = 1
    for i in range(1,N + 1):
        fac = (fac * i) % 100
    return (fac)

assert last_Two_Digits(7) == 40
assert last_Two_Digits(5) == 20
assert last_Two_Digits(2) == 2

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


import re
def remove_multiple_spaces(text1):
  return (re.sub(' +',' ',text1))

assert remove_multiple_spaces('Google      Assistant') == 'Google Assistant'

assert remove_multiple_spaces('Quad      Core') == 'Quad Core'

assert remove_multiple_spaces('ChromeCast      Built-in') == 'ChromeCast Built-in'

Write a function to remove multiple spaces in a string by using regex.


def extract_unique(test_dict):
  res = list(sorted({ele for val in test_dict.values() for ele in val}))
  return res

Write a function to extract unique values from the given dictionary values.


def check_greater(test_tup1, test_tup2):
  res = all(x < y for x, y in zip(test_tup1, test_tup2))
  return (res)

assert check_greater((1, 2, 3), (2, 1, 4)) == False

assert check_greater((4, 5, 6), (5, 6, 7)) == True

Write a function to check if each element of the second tuple is greater than its corresponding index in the first tuple.


def zip_list(list1,list2):
 result = list(map(list.__add__, list1, list2))
 return result

Write a function to zip two given lists of lists.


def count_even(array_nums):
   count_even = len(list(filter(lambda x: (x%2 == 0) , array_nums)))
   return count_even

Write a function to find number of even elements in the given list using lambda function.


def sort_dict_item(test_dict):
  res = {key: test_dict[key] for key in sorted(test_dict.keys(), key = lambda ele: ele[1] * ele[0])}
  return  (res)

Write a function to sort dictionary items by tuple product of keys for the given dictionary with tuple keys.


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("1111","0100") == "Not Possible"

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


def count_range_in_list(li, min, max):
	ctr = 0
	for x in li:
		if min <= x <= max:
			ctr += 1
	return ctr

Write a function to count the number of elements in a list which are within a specific range.


def equilibrium_index(arr):
  total_sum = sum(arr)
  left_sum=0
  for i, num in enumerate(arr):
    total_sum -= num
    if left_sum == total_sum:
      return i
    left_sum += num
  return -1

assert equilibrium_index([1, 2, 3, 4, 1, 2, 3]) == 3

assert equilibrium_index([1, 2, 3]) == -1

Write a function to find the equilibrium index of the given array.


def find_ind(key, i, n,
			k, arr):
	ind = -1
	start = i + 1
	end = n - 1;
	while (start < end):
		mid = int(start +
				(end - start) / 2)
		if (arr[mid] - key <= k):
			ind = mid
			start = mid + 1
		else:
			end = mid
	return ind
def removals(arr, n, k):
	ans = n - 1
	arr.sort()
	for i in range(0, n):
		j = find_ind(arr[i], i,
					n, k, arr)
		if (j != -1):
			ans = min(ans, n -
						(j - i + 1))
	return ans

Write a function to find the minimum number of elements that should be removed such that amax-amin<=k.


def is_key_present(d,x):
  if x in d:
    return True
  else:
     return False

Write a function to check whether the given key is present in the dictionary or not.


def harmonic_sum(n):
  if n < 2:
    return 1
  else:
    return 1 / n + (harmonic_sum(n - 1))

Write a function to calculate the harmonic sum of n-1.


def sort_sublists(list1):
      list1.sort()
      list1.sort(key=len)
      return  list1

Write a function to sort a list of lists by length and value.


def is_subset(arr1, m, arr2, n):
	hashset = set()
	for i in range(0, m):
		hashset.add(arr1[i])
	for i in range(0, n):
		if arr2[i] in hashset:
			continue
		else:
			return False
	return True

Write a function to find whether an array is subset of another array.


def count_Set_Bits(n) :
    n += 1;
    powerOf2 = 2;
    cnt = n // 2;
    while (powerOf2 <= n) :
        totalPairs = n // powerOf2;
        cnt += (totalPairs // 2) * powerOf2;
        if (totalPairs & 1) :
            cnt += (n % powerOf2)
        else :
            cnt += 0
        powerOf2 <<= 1;
    return cnt;

assert count_Set_Bits(16) == 33
assert count_Set_Bits(2) == 2
assert count_Set_Bits(14) == 28

Write a python function to count the total set bits from 1 to n.


def Convert(string):
    li = list(string.split(" "))
    return li

assert Convert('python program') == ['python','program']

assert Convert('Data Analysis') ==['Data','Analysis']

assert Convert('Hadoop Training') == ['Hadoop','Training']

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


from collections import defaultdict
def get_unique(test_list):
  res = defaultdict(list)
  for sub in test_list:
    res[sub[1]].append(sub[0])
  res = dict(res)
  res_dict = dict()
  for key in res:
    res_dict[key] = len(list(set(res[key])))
  return (str(res_dict))

Write a function to count unique keys for each value present in the tuple.


def front_and_rear(test_tup):
  res = (test_tup[0], test_tup[-1])
  return (res)

Write a function to access the initial and last data of the given tuple record.


def product_Equal(n):
    if n < 10:
        return False
    prodOdd = 1; prodEven = 1
    while n > 0:
        digit = n % 10
        prodOdd *= digit
        n = n//10
        if n == 0:
            break;
        digit = n % 10
        prodEven *= digit
        n = n//10
    if prodOdd == prodEven:
        return True
    return False

assert product_Equal(2841) == True
assert product_Equal(1234) == False
assert product_Equal(1212) == False

Write a python function to check whether the product of digits of a number at even and odd places is equal or not.


import itertools
def remove_duplicate(list1):
 list.sort(list1)
 remove_duplicate = list(list1 for list1,_ in itertools.groupby(list1))
 return remove_duplicate

Write a function to remove duplicates from a list of lists.


def check_valid(test_tup):
  res = not any(map(lambda ele: not ele, test_tup))
  return (res)

assert check_valid((True, True, True, True) ) == True

assert check_valid((True, False, True, True) ) == False

Write a function to check if the given tuple contains all valid values or not.


def count_Fac(n):
    m = n
    count = 0
    i = 2
    while((i * i) <= m):
        total = 0
        while (n % i == 0):
            n /= i
            total += 1
        temp = 0
        j = 1
        while((temp + j) <= total):
            temp += j
            count += 1
            j += 1
        i += 1
    if (n != 1):
        count += 1
    return count

assert count_Fac(24) == 3
assert count_Fac(12) == 2
assert count_Fac(4) == 1

Write a python function to count the number of distinct power of prime factor of given number.


def str_to_tuple(test_str):
  res = tuple(map(int, test_str.split(', ')))
  return (res)

Write a function to convert the given string of integers into a tuple.


def rombus_perimeter(a):
  perimeter=4*a
  return perimeter

assert rombus_perimeter(10)==40
assert rombus_perimeter(5)==20
assert rombus_perimeter(4)==16

Write a function to find the perimeter of a rombus.


import math
import sys
def sd_calc(data):
    n = len(data)
    if n <= 1:
        return 0.0
    mean, sd = avg_calc(data), 0.0
    for el in data:
        sd += (float(el) - mean)**2
    sd = math.sqrt(sd / float(n-1))
    return sd
def avg_calc(ls):
    n, mean = len(ls), 0.0
    if n <= 1:
        return ls[0]
    for el in ls:
        mean = mean + float(el)
    mean = mean / float(n)
    return mean

Write a function to calculate the standard deviation.


def alternate_elements(list1):
    result=[]
    for item in list1[::2]:
        result.append(item)
    return result

assert alternate_elements(["red", "black", "white", "green", "orange"])==['red', 'white', 'orange']

Write a function to create a list taking alternate elements from another given list.


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

assert text_match("ac")==('Found a match!')

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

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


def add_dict_to_tuple(test_tup, test_dict):
  test_tup = list(test_tup)
  test_tup.append(test_dict)
  test_tup = tuple(test_tup)
  return (test_tup)

Write a function to add a dictionary to the tuple.


M = 100
def maxAverageOfPath(cost, N):
	dp = [[0 for i in range(N + 1)] for j in range(N + 1)]
	dp[0][0] = cost[0][0]
	for i in range(1, N):
		dp[i][0] = dp[i - 1][0] + cost[i][0]
	for j in range(1, N):
		dp[0][j] = dp[0][j - 1] + cost[0][j]
	for i in range(1, N):
		for j in range(1, N):
			dp[i][j] = max(dp[i - 1][j],
						dp[i][j - 1]) + cost[i][j]
	return dp[N - 1][N - 1] / (2 * N - 1)

Write a function to find a path with the maximum average over all existing paths for the given square matrix of size n*n.


def filter_data(students,h,w):
    result = {k: s for k, s in students.items() if s[0] >=h and s[1] >=w}
    return result

Write a function to filter the height and width of students which are stored in a dictionary.


from operator import eq
def count_same_pair(nums1, nums2):
    result = sum(map(eq, nums1, nums2))
    return result

Write a function to count the same pair in two given lists using map function.


def power_base_sum(base, power):
    return sum([int(i) for i in str(pow(base, power))])

assert power_base_sum(2,100)==115
assert power_base_sum(8,10)==37
assert power_base_sum(8,15)==62

Write a function to calculate the sum of all digits of the base to the specified power.


import re
def extract_quotation(text1):
  return (re.findall(r'"(.*?)"', text1))

assert extract_quotation('Cortex "A53" Based "multi" tasking "Processor"') == ['A53', 'multi', 'Processor']

assert extract_quotation('Cast your "favorite" entertainment "apps"') == ['favorite', 'apps']

assert extract_quotation('Watch content "4k Ultra HD" resolution with "HDR 10" Support') == ['4k Ultra HD', 'HDR 10']

Write a function to extract values between quotation marks of the given string by using regex.


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

Write a function to multiply the adjacent elements of the given tuple.


import re
def remove_char(S):
  result = re.sub('[\W_]+', '', S)
  return result

assert remove_char("123abcjw:, .@! eiw") == '123abcjweiw'

assert remove_char("Hello1234:, ! Howare33u") == 'Hello1234Howare33u'

assert remove_char("Cool543Triks@:, Make@987Trips") == 'Cool543TriksMake987Trips'

Write a function to remove all characters except letters and numbers using regex


def sum_list(lst1,lst2):
  res_list = [lst1[i] + lst2[i] for i in range(len(lst1))]
  return res_list

Write a function to sum elements in two lists.


def add_list(nums1,nums2):
  result = map(lambda x, y: x + y, nums1, nums2)
  return list(result)

Write a function to add two lists using map and lambda function.


from itertools import groupby
def consecutive_duplicates(nums):
    return [key for key, group in groupby(nums)]

assert consecutive_duplicates(['a', 'a', 'b', 'c', 'd', 'd'])==['a', 'b', 'c', 'd']

Write a function to remove consecutive duplicates of a given list.


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

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


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

assert replace_specialchar('Python language, Programming language.')==('Python:language::Programming:language:')

assert replace_specialchar('a b c,d e f')==('a:b:c:d:e:f')

assert replace_specialchar('ram reshma,ram rahim')==('ram:reshma:ram:rahim')

Write a function to replace all occurrences of spaces, commas, or dots with a colon.


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

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


def sum_Of_Subarray_Prod(arr,n):
    ans = 0
    res = 0
    i = n - 1
    while (i >= 0):
        incr = arr[i]*(1 + res)
        ans += incr
        res = incr
        i -= 1
    return (ans)

assert sum_Of_Subarray_Prod([1,2,3],3) == 20

assert sum_Of_Subarray_Prod([1,2],2) == 5

assert sum_Of_Subarray_Prod([1,2,3,4],4) == 84

Write a python function to find sum of products of all possible subarrays.


def set_middle_bits(n):
    n |= n >> 1;
    n |= n >> 2;
    n |= n >> 4;
    n |= n >> 8;
    n |= n >> 16;
    return (n >> 1) ^ 1
def toggle_middle_bits(n):
    if (n == 1):
        return 1
    return n ^ set_middle_bits(n)

assert toggle_middle_bits(9) == 15
assert toggle_middle_bits(10) == 12
assert toggle_middle_bits(11) == 13

Write a python function to toggle bits of the number except the first and the last bit.


import bisect
def left_insertion(a, x):
    i = bisect.bisect_left(a, x)
    return i

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

Write a function to locate the left insertion point for a specified value in sorted order.


import re
regex = '^[aeiouAEIOU][A-Za-z0-9_]*'
def check_str(string):
	if(re.search(regex, string)):
		return ("Valid")
	else:
		return ("Invalid")

assert check_str("annie") == 'Valid'
assert check_str("dawood") == 'Invalid'
assert check_str("Else") == 'Valid'

Write a function to check whether the given string is starting with a vowel or not using regex.


def geometric_sum(n):
  if n < 0:
    return 0
  else:
    return 1 / (pow(2, n)) + geometric_sum(n - 1)

assert geometric_sum(7) == 1.9921875
assert geometric_sum(4) == 1.9375
assert geometric_sum(8) == 1.99609375

Write a function to calculate the geometric sum of n-1.


import math
def find_Index(n):
    x = math.sqrt(2 * math.pow(10,(n - 1)));
    return round(x);

assert find_Index(2) == 4
assert find_Index(3) == 14
assert find_Index(4) == 45

Write a python function to find the index of smallest triangular number with n digits.


def tuple_to_dict(test_tup):
  res = dict(test_tup[idx : idx + 2] for idx in range(0, len(test_tup), 2))
  return (res)

Write a function to convert the given tuple to a key-value dictionary using adjacent elements.


def all_Characters_Same(s) :
    n = len(s)
    for i in range(1,n) :
        if s[i] != s[0] :
            return False
    return True

assert all_Characters_Same("python") == False

assert all_Characters_Same("aaa") == True

assert all_Characters_Same("data") == False

Write a python function to check whether all the characters are same or not.


import math
def area_tetrahedron(side):
  area = math.sqrt(3)*(side*side)
  return area

Write a function to caluclate the area of a tetrahedron.


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

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


def check_none(test_tup):
  res = any(map(lambda ele: ele is None, test_tup))
  return (res)

assert check_none((10, 4, 5, 6, None)) == True

assert check_none((7, 8, 9, 11, 14)) == False

assert check_none((1, 2, 3, 4, None)) == True

Write a function to check if the given tuple has any none value or not.


def divisible_by_digits(startnum, endnum):
    return [n for n in range(startnum, endnum+1) \
                if not any(map(lambda x: int(x) == 0 or n%int(x) != 0, str(n)))]

Write a function to find numbers within a given range where every number is divisible by every digit it contains.


def sector_area(r,a):
    pi=22/7
    if a >= 360:
        return None
    sectorarea = (pi*r**2) * (a/360)
    return sectorarea

Write a function to find area of a sector.


def lcs_of_three(X, Y, Z, m, n, o):
	L = [[[0 for i in range(o+1)] for j in range(n+1)]
		for k in range(m+1)]
	for i in range(m+1):
		for j in range(n+1):
			for k in range(o+1):
				if (i == 0 or j == 0 or k == 0):
					L[i][j][k] = 0
				elif (X[i-1] == Y[j-1] and
					X[i-1] == Z[k-1]):
					L[i][j][k] = L[i-1][j-1][k-1] + 1
				else:
					L[i][j][k] = max(max(L[i-1][j][k],
					L[i][j-1][k]),
									L[i][j][k-1])
	return L[m][n][o]

assert lcs_of_three('AGGT12', '12TXAYB', '12XBA', 6, 7, 5) == 2

assert lcs_of_three('Reels', 'Reelsfor', 'ReelsforReels', 5, 8, 13) == 5

assert lcs_of_three('abcd1e2', 'bc12ea', 'bd1ea', 7, 6, 5) == 3

Write a function to find the longest common subsequence for the given three string sequence.


import re
def capital_words_spaces(str1):
  return re.sub(r"(\w)([A-Z])", r"\1 \2", str1)

assert capital_words_spaces("Python") == 'Python'

assert capital_words_spaces("PythonProgrammingExamples") == 'Python Programming Examples'

assert capital_words_spaces("GetReadyToBeCodingFreak") == 'Get Ready To Be Coding Freak'

Write a function to put spaces between words starting with capital letters in a given string by using regex.


def sort_numeric_strings(nums_str):
    result = [int(x) for x in nums_str]
    result.sort()
    return result

Write a function to sort a given list of strings of numbers numerically.


def add_tuple(test_list, test_tup):
  test_list += test_tup
  return (test_list)

Write a function to add the given tuple to the given list.


def check_min_heap(arr, i):
    if 2 * i + 2 > len(arr):
        return True
    left_child = (arr[i] <= arr[2 * i + 1]) and check_min_heap(arr, 2 * i + 1)
    right_child = (2 * i + 2 == len(arr)) or (arr[i] <= arr[2 * i + 2]
                                      and check_min_heap(arr, 2 * i + 2))
    return left_child and right_child

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

assert check_min_heap([2, 10, 4, 5, 3, 15], 0) == False

Write a function to check if the given array represents min heap or not.


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

assert jacobsthal_num(5) == 11
assert jacobsthal_num(2) == 1
assert jacobsthal_num(4) == 5

Write a function to find the nth jacobsthal number.


def min_k(test_list, K):
  res = sorted(test_list, key = lambda x: x[1])[:K]
  return (res)

Write a function to find minimum k records from tuple list.


def extract_index_list(l1, l2, l3):
    result = []
    for m, n, o in zip(l1, l2, l3):
        if (m == n == o):
            result.append(m)
    return result

Write a function to find common index elements from three lists.


def second_smallest(numbers):
  if (len(numbers)<2):
    return
  if ((len(numbers)==2)  and (numbers[0] == numbers[1]) ):
    return
  dup_items = set()
  uniq_items = []
  for x in numbers:
    if x not in dup_items:
      uniq_items.append(x)
      dup_items.add(x)
  uniq_items.sort()
  return  uniq_items[1]

Write a function to find the second smallest number in a list.


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

assert text_match_zero_one("ac")==('Found a match!')

assert text_match_zero_one("abbbba")==('Found a match!')

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


def count_reverse_pairs(test_list):
  res = sum([1 for idx in range(0, len(test_list)) for idxn in range(idx, len(
	test_list)) if test_list[idxn] == str(''.join(list(reversed(test_list[idx]))))])
  return str(res)

assert count_reverse_pairs(["julia", "best", "tseb", "for", "ailuj"])== '2'

assert count_reverse_pairs(["geeks", "best", "for", "skeeg"]) == '1'

assert count_reverse_pairs(["makes", "best", "sekam", "for", "rof"]) == '2'

Write a function to count the pairs of reverse strings in the given string list.


def unique_sublists(list1):
    result ={}
    for l in  list1:
        result.setdefault(tuple(l), list()).append(1)
    for a, b in result.items():
        result[a] = sum(b)
    return result

assert unique_sublists([['green', 'orange'], ['black'], ['green', 'orange'], ['white']])=={('green', 'orange'): 2, ('black',): 1, ('white',): 1}

Write a function to count number of unique lists within a list.


def is_decimal(num):
    import re
    dnumre = re.compile(r"""^[0-9]+(\.[0-9]{1,2})?$""")
    result = dnumre.search(num)
    return bool(result)

assert is_decimal('123.11')==True
assert is_decimal('e666.86')==False
assert is_decimal('3.124587')==False

Write a function to check a decimal with a precision of 2.


def unique_Element(arr,n):
    s = set(arr)
    if (len(s) == 1):
        return ('YES')
    else:
        return ('NO')

assert unique_Element([1,1,1],3) == 'YES'

assert unique_Element([1,2,1,2],4) == 'NO'

assert unique_Element([1,2,3,4,5],5) == 'NO'

Write a python function to check whether an array contains only one distinct element or not.


def arc_length(d,a):
    pi=22/7
    if a >= 360:
        return None
    arclength = (pi*d) * (a/360)
    return arclength

Write a function to caluclate arc length of an angle.


def check_monthnumber_number(monthnum3):
  if(monthnum3==4 or monthnum3==6 or monthnum3==9 or monthnum3==11):
    return True
  else:
    return False

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


def find_Min_Diff(arr,n):
    arr = sorted(arr)
    diff = 10**20
    for i in range(n-1):
        if arr[i+1] - arr[i] < diff:
            diff = arr[i+1] - arr[i]
    return diff

Write a python function to find the minimum difference between any two elements in a given array.


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

assert number_ctr('program2bedone') == 1

Write a python function to count numeric values in a given string.


import math
def is_polite(n):
	n = n + 1
	return (int)(n+(math.log((n + math.log(n, 2)), 2)))

assert is_polite(7) == 11
assert is_polite(4) == 7
assert is_polite(9) == 13

Write a function to find nth polite number.


def pair_wise(l1):
    temp = []
    for i in range(len(l1) - 1):
        current_element, next_element = l1[i], l1[i + 1]
        x = (current_element, next_element)
        temp.append(x)
    return temp

Write a function to iterate over all pairs of consecutive items in a given list.


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

assert get_Pairs_Count([1,-2,3],3,1) == 1

Write a python function to count the number of pairs whose sum is equal to ‘sum’.


def check_Odd_Parity(x):
    parity = 0
    while (x != 0):
        x = x & (x - 1)
        parity += 1
    if (parity % 2 == 1):
        return True
    else:
        return False

assert check_Odd_Parity(13) == True
assert check_Odd_Parity(21) == True
assert check_Odd_Parity(18) == False

Write a python function to check for odd parity of a given number.


def Diff(li1,li2):
    return (list(list(set(li1)-set(li2)) + list(set(li2)-set(li1))))

Write a python function to get the difference between two lists.


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)
    return sm

assert odd_Num_Sum(2) == 82
assert odd_Num_Sum(3) == 707
assert odd_Num_Sum(4) == 3108

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


from collections import deque
def check_expression(exp):
    if len(exp) & 1:
        return False
    stack = deque()
    for ch in exp:
        if ch == '(' or ch == '{' or ch == '[':
            stack.append(ch)
        if ch == ')' or ch == '}' or ch == ']':
            if not stack:
                return False
            top = stack.pop()
            if (top == '(' and ch != ')') or (top == '{' and ch != '}' or (top == '[' and ch != ']')):
                return False
    return not stack

assert check_expression("{()}[{}]") == True

assert check_expression("{()}[{]") == False

assert check_expression("{()}[{}][]({})") == True

Write a function to check if the given expression is balanced or not.


def remove_length(test_str, K):
  temp = test_str.split()
  res = [ele for ele in temp if len(ele) != K]
  res = ' '.join(res)
  return (res)

assert remove_length('The person is most value tet', 3) == 'person is most value'

assert remove_length('If you told me about this ok', 4) == 'If you me about ok'

assert remove_length('Forces of darkeness is come into the play', 4) == 'Forces of darkeness is the'

Write a function to remove all the words with k length in the given string.


import re
def occurance_substring(text,pattern):
 for match in re.finditer(pattern, text):
    s = match.start()
    e = match.end()
    return (text[s:e], s, e)

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

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

assert occurance_substring('python programming,programming language','language')==('language', 31, 39)

Write a function to find the occurrence and position of the substrings within a string.


import re
regex = '^[a-z0-9]+[\._]?[a-z0-9]+[@]\w+[.]\w{2,3}$'
def check_email(email):
	if(re.search(regex,email)):
		return ("Valid Email")
	else:
		return ("Invalid Email")

assert check_email("ankitrai326@gmail.com") == 'Valid Email'

assert check_email("my.ownsite@ourearth.org") == 'Valid Email'

assert check_email("ankitaoie326.com") == 'Invalid Email'

Write a function to check if the string is a valid email address or not using regex.


def odd_position(nums):
	return all(nums[i]%2==i%2 for i in range(len(nums)))

Write a python function to check whether every odd index contains odd numbers of a given list.


def count_vowels(test_str):
  res = 0
  vow_list = ['a', 'e', 'i', 'o', 'u']
  for idx in range(1, len(test_str) - 1):
    if test_str[idx] not in vow_list and (test_str[idx - 1] in vow_list or test_str[idx + 1] in vow_list):
      res += 1
  if test_str[0] not in vow_list and test_str[1] in vow_list:
    res += 1
  if test_str[-1] not in vow_list and test_str[-2] in vow_list:
    res += 1
  return (res)

assert count_vowels('bestinstareels') == 7

assert count_vowels('partofthejourneyistheend') == 12

Write a function to count those characters which have vowels as their neighbors in the given string.


def find_Sum(arr,n):
    arr.sort()
    sum = arr[0]
    for i in range(0,n-1):
        if (arr[i] != arr[i+1]):
            sum = sum + arr[i+1]
    return sum

Write a python function to find the sum of non-repeated elements in a given array.


from itertools import groupby
def pack_consecutive_duplicates(list1):
    return [list(group) for key, group in groupby(list1)]

Write a function to pack consecutive duplicates of a given list elements into sublists.


def unique_sublists(list1):
    result ={}
    for l in list1:
        result.setdefault(tuple(l), list()).append(1)
    for a, b in result.items():
        result[a] = sum(b)
    return result

assert unique_sublists([['green', 'orange'], ['black'], ['green', 'orange'], ['white']])=={('green', 'orange'): 2, ('black',): 1, ('white',): 1}

Write a function to count the number of unique lists within a list.


from itertools import combinations
def find_combinations(test_list):
  res = [(b1 + a1, b2 + a2) for (a1, a2), (b1, b2) in combinations(test_list, 2)]
  return (res)

Write a function to find the combinations of sums with tuples in the given tuple list.


import math
def count_Divisors(n) :
    count = 0
    for i in range(1, (int)(math.sqrt(n)) + 2) :
        if (n % i == 0) :
            if( n // i == i) :
                count = count + 1
            else :
                count = count + 2
    if (count % 2 == 0) :
        return ("Even")
    else :
        return ("Odd")

assert count_Divisors(10) == "Even"
assert count_Divisors(100) == "Odd"
assert count_Divisors(125) == "Even"

Write a python function to check whether the count of divisors is even or odd.


def Odd_Length_Sum(arr):
    Sum = 0
    l = len(arr)
    for i in range(l):
        Sum += ((((i + 1) *(l - i) + 1) // 2) * arr[i])
    return Sum

assert Odd_Length_Sum([1,2,4]) == 14
assert Odd_Length_Sum([1,2,1,2]) == 15
assert Odd_Length_Sum([1,7]) == 8

Write a python function to find the sum of all odd length subarrays.


Write a function to convert rgb color to hsv color.


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

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


def tuple_str_int(test_str):
  res = tuple(int(num) for num in test_str.replace('(', '').replace(')', '').replace('...', '').split(', '))
  return (res)

Write a function to convert tuple string to integer tuple.


import bisect
def right_insertion(a, x):
    i = bisect.bisect_right(a, x)
    return i

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

Write a function to locate the right insertion point for a specified value in sorted order.


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

assert text_match_three("abbbba")==('Found a match!')

Write a function that matches a string that has an a followed by three 'b'.


def new_tuple(test_list, test_str):
  res = tuple(test_list + [test_str])
  return (res)

assert new_tuple(["WEB", "is"], "best") == ('WEB', 'is', 'best')

assert new_tuple(["We", "are"], "Developers") == ('We', 'are', 'Developers')

assert new_tuple(["Part", "is"], "Wrong") == ('Part', 'is', 'Wrong')

Write a function to create a new tuple from the given string and list.


from math import tan, pi
def perimeter_polygon(s,l):
  perimeter = s*l
  return perimeter

assert perimeter_polygon(4,20)==80
assert perimeter_polygon(10,15)==150
assert perimeter_polygon(9,7)==63

Write a function to calculate the perimeter of a regular polygon.


def even_position(nums):
	return all(nums[i]%2==i%2 for i in range(len(nums)))

assert even_position([3,2,1]) == False
assert even_position([1,2,3]) == False
assert even_position([2,1,4]) == True

Write a python function to check whether every even index contains even numbers of a given list.


def remove_nested(test_tup):
  res = tuple()
  for count, ele in enumerate(test_tup):
    if not isinstance(ele, tuple):
      res = res + (ele, )
  return (res)

Write a function to remove the nested record from the given tuple.


def count_list(input_list):
    return len(input_list)

Write a python function to count the number of lists in a given number of lists.


def last(arr,x,n):
    low = 0
    high = n - 1
    res = -1
    while (low <= high):
        mid = (low + high) // 2
        if arr[mid] > x:
            high = mid - 1
        elif arr[mid] < x:
            low = mid + 1
        else:
            res = mid
            low = mid + 1
    return res

Write a python function to find the last position of an element in a sorted array.


import re
def text_starta_endb(text):
        patterns = 'a.*?b$'
        if re.search(patterns,  text):
                return 'Found a match!'
        else:
                return('Not matched!')

assert text_starta_endb("aabbbb")==('Found a match!')

Write a function that matches a string that has an 'a' followed by anything, ending in 'b'.


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

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


def return_sum(dict):
  sum = 0
  for i in dict.values():
    sum = sum + i
  return sum

Write function to find the sum of all items in the given dictionary.


def sum_Odd(n):
    terms = (n + 1)//2
    sum1 = terms * terms
    return sum1
def sum_in_Range(l,r):
    return sum_Odd(r) - sum_Odd(l - 1)

assert sum_in_Range(2,5) == 8
assert sum_in_Range(5,7) == 12
assert sum_in_Range(7,13) == 40

Write a python function to find the sum of all odd natural numbers within the range l and r.


def _sum(arr):
    sum=0
    for i in arr:
        sum = sum + i
    return(sum)

Write a python function to find the sum of an array.


INT_BITS = 32
def left_Rotate(n,d):
    return (n << d)|(n >> (INT_BITS - d))

assert left_Rotate(16,2) == 64
assert left_Rotate(10,2) == 40
assert left_Rotate(99,3) == 792

Write a python function to left rotate the bits of a given number.


import re
def remove_all_spaces(text):
 return (re.sub(r'\s+', '',text))

assert remove_all_spaces('python  program')==('pythonprogram')

assert remove_all_spaces('python   programming    language')==('pythonprogramminglanguage')

Write a function to remove all whitespaces from a string.


def test_three_equal(x,y,z):
  result= set([x,y,z])
  if len(result)==3:
    return 0
  else:
    return (4-len(result))

assert test_three_equal(1,1,1) == 3
assert test_three_equal(-1,-2,-3) == 0
assert test_three_equal(1,2,2) == 2

Write a python function to count the number of equal numbers from three given integers.


def count_Rotation(arr,n):
    for i in range (1,n):
        if (arr[i] < arr[i - 1]):
            return i
    return 0

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

Write a python function to count the number of rotations required to generate a sorted array.


def is_Perfect_Square(n) :
    i = 1
    while (i * i<= n):
        if ((n % i == 0) and (n / i == i)):
            return True
        i = i + 1
    return False

assert is_Perfect_Square(10) == False
assert is_Perfect_Square(36) == True
assert is_Perfect_Square(14) == False

Write a python function to check whether the given number is a perfect square or not.


def is_Product_Even(arr,n):
    for i in range(0,n):
        if ((arr[i] & 1) == 0):
            return True
    return False

assert is_Product_Even([1,2,3],3) == True

assert is_Product_Even([1,2,1,4],4) == True

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

Write a python function to check whether the product of numbers is even or not.


def max_sum_list(lists):
 return max(lists, key=sum)

Write a function to find the list in a list of lists whose sum of elements is the highest.


def max_run_uppercase(test_str):
  cnt = 0
  res = 0
  for idx in range(0, len(test_str)):
    if test_str[idx].isupper():
      cnt += 1
    else:
      res = cnt
      cnt = 0
  if test_str[len(test_str) - 1].isupper():
    res = cnt
  return (res)

assert max_run_uppercase('GeMKSForGERksISBESt') == 5

assert max_run_uppercase('PrECIOusMOVemENTSYT') == 6

assert max_run_uppercase('GooGLEFluTTER') == 4

Write a function to find maximum run of uppercase characters in the given string.


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

assert first_odd([1,3,5]) == 1
assert first_odd([2,4,1,3]) == 1
assert first_odd ([8,9,1]) == 9

Write a python function to find the first odd number in a given list of numbers.


def check_K(test_tup, K):
  res = False
  for ele in test_tup:
    if ele == K:
      res = True
      break
  return (res)

Write a function to check if the given tuples contain the k or not.


def check_smaller(test_tup1, test_tup2):
  res = all(x > y for x, y in zip(test_tup1, test_tup2))
  return (res)

assert check_smaller((1, 2, 3), (2, 3, 4)) == False

assert check_smaller((4, 5, 6), (3, 4, 5)) == True

Write a function to check if each element of second tuple is smaller than its corresponding index in first tuple.


from collections import Counter
def count_variable(a,b,c,d):
  c = Counter(p=a, q=b, r=c, s=d)
  return list(c.elements())

Write a function to iterate over elements repeating each as many times as its count.


def check_identical(test_list1, test_list2):
  res = test_list1 == test_list2
  return (res)

Write a function to check if two lists of tuples are identical or not.


import re
def road_rd(street):
  return (re.sub('Road$', 'Rd.', street))

assert road_rd("ravipadu Road")==('ravipadu Rd.')

assert road_rd("palnadu Road")==('palnadu Rd.')

assert road_rd("eshwar enclave Road")==('eshwar enclave Rd.')

Write a function to abbreviate 'road' as 'rd.' in a given string.


def string_length(str1):
    count = 0
    for char in str1:
        count += 1
    return count

assert string_length('python')==6
assert string_length('program')==7
assert string_length('language')==8

Write a function to find length of the string.


def rombus_area(p,q):
  area=(p*q)/2
  return area

assert rombus_area(10,20)==100
assert rombus_area(10,5)==25
assert rombus_area(4,2)==4

Write a function to find the area of a rombus.


def sort_by_dnf(arr, n):
  low=0
  mid=0
  high=n-1
  while mid <= high:
    if arr[mid] == 0:
      arr[low], arr[mid] = arr[mid], arr[low]
      low = low + 1
      mid = mid + 1
    elif arr[mid] == 1:
      mid = mid + 1
    else:
      arr[mid], arr[high] = arr[high], arr[mid]
      high = high - 1
  return arr

Write a function to sort the given array without using any sorting algorithm. the given array consists of only 0, 1, and 2.


def clear_tuple(test_tup):
  temp = list(test_tup)
  temp.clear()
  test_tup = tuple(temp)
  return (test_tup)

Write a function to clear the values of the given tuples.


def div_of_nums(nums,m,n):
 result = list(filter(lambda x: (x % m == 0 or x % n == 0), nums))
 return result

Write a function to find numbers divisible by m or n from a list of numbers using lambda function.


def lower_ctr(str):
      lower_ctr= 0
      for i in range(len(str)):
          if str[i] >= 'a' and str[i] <= 'z': lower_ctr += 1
      return  lower_ctr

assert lower_ctr('abc') == 3
assert lower_ctr('string') == 6
assert lower_ctr('Python') == 5

Write a python function to count lower case letters in a given string.


def count_duplic(lists):
    element = []
    frequency = []
    if not lists:
        return element
    running_count = 1
    for i in range(len(lists)-1):
        if lists[i] == lists[i+1]:
            running_count += 1
        else:
            frequency.append(running_count)
            element.append(lists[i])
            running_count = 1
    frequency.append(running_count)
    element.append(lists[i+1])
    return element,frequency

Write a function to count the frequency of consecutive duplicate elements in a given list of numbers.


def check_monthnum_number(monthnum1):
  if monthnum1 == 2:
    return True
  else:
    return False

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

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


import collections as ct
def merge_dictionaries(dict1,dict2):
    merged_dict = dict(ct.ChainMap({}, dict1, dict2))
    return merged_dict

assert merge_dictionaries({ "R": "Red", "B": "Black", "P": "Pink" }, { "G": "Green", "W": "White" })=={'B': 'Black', 'R': 'Red', 'P': 'Pink', 'G': 'Green', 'W': 'White'}

assert merge_dictionaries({ "R": "Red", "B": "Black", "P": "Pink" },{ "O": "Orange", "W": "White", "B": "Black" })=={'O': 'Orange', 'P': 'Pink', 'B': 'Black', 'W': 'White', 'R': 'Red'}

assert merge_dictionaries({ "G": "Green", "W": "White" },{ "O": "Orange", "W": "White", "B": "Black" })=={'W': 'White', 'O': 'Orange', 'G': 'Green', 'B': 'Black'}

Write a function to merge two dictionaries into a single expression.


import re
def pass_validity(p):
 x = True
 while x:
    if (len(p)<6 or len(p)>12):
        break
    elif not re.search("[a-z]",p):
        break
    elif not re.search("[0-9]",p):
        break
    elif not re.search("[A-Z]",p):
        break
    elif not re.search("[$#@]",p):
        break
    elif re.search("\s",p):
        break
    else:
        return True
        x=False
        break

 if x:
    return False

Write a function to return true if the password is valid.


import re
def check_substring(string, sample) :
  if (sample in string):
      y = "\A" + sample
      x = re.search(y, string)
      if x :
          return ("string starts with the given substring")
      else :
          return ("string doesnt start with the given substring")
  else :
      return ("entered string isnt a substring")

assert check_substring("dreams for dreams makes life fun", "makes") == 'string doesnt start with the given substring'

assert check_substring("Hi there how are you Hi alex", "Hi") == 'string starts with the given substring'

assert check_substring("Its been a long day", "been") == 'string doesnt start with the given substring'

Write a function to check if the given string starts with a substring using regex.


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

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


def access_elements(nums, list_index):
    result = [nums[i] for i in list_index]
    return result

Write a python function to access multiple elements of specified index from a given list.


def check_Type_Of_Triangle(a,b,c):
    sqa = pow(a,2)
    sqb = pow(b,2)
    sqc = pow(c,2)
    if (sqa == sqa + sqb or sqb == sqa + sqc or sqc == sqa + sqb):
        return ("Right-angled Triangle")
    elif (sqa > sqc + sqb or sqb > sqa + sqc or sqc > sqa + sqb):
        return ("Obtuse-angled Triangle")
    else:
        return ("Acute-angled Triangle")

assert check_Type_Of_Triangle(1,2,3) == "Obtuse-angled Triangle"

assert check_Type_Of_Triangle(2,2,2) == "Acute-angled Triangle"

assert check_Type_Of_Triangle(1,0,1) == "Right-angled Triangle"

Write a python function to find the type of triangle from the given sides.


def sum_column(list1, C):
    result = sum(row[C] for row in list1)
    return result

Write a function to sum a specific column of a list in a given list of lists.


def count_alpha_dig_spl(string):
  alphabets=digits = special = 0
  for i in range(len(string)):
    if(string[i].isalpha()):
        alphabets = alphabets + 1
    elif(string[i].isdigit()):
        digits = digits + 1
    else:
        special = special + 1
  return (alphabets,digits,special)

Write a function to count alphabets,digits and special charactes in a given string.


from collections import Counter

def second_frequent(input):
	dict = Counter(input)
	value = sorted(dict.values(), reverse=True)
	second_large = value[1]
	for (key, val) in dict.items():
		if val == second_large:
			return (key)

assert second_frequent(['aaa','bbb','ccc','bbb','aaa','aaa']) == 'bbb'

assert second_frequent(['abc','bcd','abc','bcd','bcd','bcd']) == 'abc'

assert second_frequent(['cdma','gsm','hspa','gsm','cdma','cdma']) == 'gsm'

Write a function to find out the second most repeated (or frequent) string in the given sequence.


import math
def round_up(a, digits):
    n = 10**-digits
    return round(math.ceil(a / n) * n, digits)

Write a function to round up a number to specific digits.


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

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


import re
def extract_max(input):
	numbers = re.findall('\d+',input)
	numbers = map(int,numbers)
	return max(numbers)

assert extract_max('100klh564abc365bg') == 564

assert extract_max('hello300how546mer231') == 546

assert extract_max('its233beenalong343journey234') == 343

Write a function to extract the maximum numeric value from a string by using regex.


def get_key(dict):
    list = []
    for key in dict.keys():
        list.append(key)
    return list

Write a function to get dictionary keys as a list.


def generate_matrix(n):
        if n<=0:
            return []
        matrix=[row[:] for row in [[0]*n]*n]
        row_st=0
        row_ed=n-1
        col_st=0
        col_ed=n-1
        current=1
        while (True):
            if current>n*n:
                break
            for c in range (col_st, col_ed+1):
                matrix[row_st][c]=current
                current+=1
            row_st+=1
            for r in range (row_st, row_ed+1):
                matrix[r][col_ed]=current
                current+=1
            col_ed-=1
            for c in range (col_ed, col_st-1, -1):
                matrix[row_ed][c]=current
                current+=1
            row_ed-=1
            for r in range (row_ed, row_st-1, -1):
                matrix[r][col_st]=current
                current+=1
            col_st+=1
        return matrix

Write a function to generate a square matrix filled with elements from 1 to n raised to the power of 2 in spiral order.


def slope(x1,y1,x2,y2):
    return (float)(y2-y1)/(x2-x1)

Write a python function to find the slope of a line.


from sys import maxsize
def max_sub_array_sum(a,size):
	max_so_far = -maxsize - 1
	max_ending_here = 0
	start = 0
	end = 0
	s = 0
	for i in range(0,size):
		max_ending_here += a[i]
		if max_so_far < max_ending_here:
			max_so_far = max_ending_here
			start = s
			end = i
		if max_ending_here < 0:
			max_ending_here = 0
			s = i+1
	return (end - start + 1)

Write a function to find length of the subarray having maximum sum.


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

assert cube_Sum(2) == 28
assert cube_Sum(3) == 153
assert cube_Sum(4) == 496

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


Write a python function to find minimum number swaps required to make two binary strings equal.


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

Write a function to sort the tuples alphabetically by the first item of each tuple.


def Check_Solution(a,b,c):
    if b == 0:
        return ("Yes")
    else:
        return ("No")

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

Write a python function to check whether the roots of a quadratic equation are numerically equal but opposite in sign or not.


def get_inv_count(arr, n):
	inv_count = 0
	for i in range(n):
		for j in range(i + 1, n):
			if (arr[i] > arr[j]):
				inv_count += 1
	return inv_count

Write a function to count the number of inversions in the given array.


def get_odd_occurence(arr, arr_size):
  for i in range(0, arr_size):
    count = 0
    for j in range(0, arr_size):
      if arr[i] == arr[j]:
        count += 1
    if (count % 2 != 0):
      return arr[i]
  return -1

Write a function to find the number which occurs for odd number of times in the given array.


import heapq
def nth_super_ugly_number(n, primes):
    uglies = [1]
    def gen(prime):
        for ugly in uglies:
            yield ugly * prime
    merged = heapq.merge(*map(gen, primes))
    while len(uglies) < n:
        ugly = next(merged)
        if ugly != uglies[-1]:
            uglies.append(ugly)
    return uglies[-1]

Write a function to find the nth super ugly number from a given prime list of size k using heap queue algorithm.


def get_Number(n, k):
    arr = [0] * n;
    i = 0;
    odd = 1;
    while (odd <= n):
        arr[i] = odd;
        i += 1;
        odd += 2;
    even = 2;
    while (even <= n):
        arr[i] = even;
        i += 1;
        even += 2;
    return arr[k - 1];

assert get_Number(8,5) == 2
assert get_Number(7,2) == 3
assert get_Number(5,2) == 3

Write a python function to find the kth element in an array containing odd elements first and then even elements.


import math
def find_Digits(n):
    if (n < 0):
        return 0;
    if (n <= 1):
        return 1;
    x = ((n * math.log10(n / math.e) + math.log10(2 * math.pi * n) /2.0));
    return math.floor(x) + 1;

assert find_Digits(7) == 4
assert find_Digits(5) == 3
assert find_Digits(4) == 2

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


def find_platform(arr, dep, n):
    arr.sort()
    dep.sort()
    plat_needed = 1
    result = 1
    i = 1
    j = 0
    while (i < n and j < n):
        if (arr[i] <= dep[j]):
            plat_needed+= 1
            i+= 1
        elif (arr[i] > dep[j]):
            plat_needed-= 1
            j+= 1
        if (plat_needed > result):
            result = plat_needed
    return result

Write a function to find the minimum number of platforms required for a railway/bus station.


Write a python function to copy a list from a singleton tuple.


def area_trapezium(base1,base2,height):
 area = 0.5 * (base1 + base2) * height
 return area

assert area_trapezium(6,9,4)==30
assert area_trapezium(10,20,30)==450
assert area_trapezium(15,25,35)==700

Write a function to find the area of a trapezium.


def Sum(N):
    SumOfPrimeDivisors = [0]*(N + 1)
    for i in range(2,N + 1) :
        if (SumOfPrimeDivisors[i] == 0) :
            for j in range(i,N + 1,i) :
                SumOfPrimeDivisors[j] += i
    return SumOfPrimeDivisors[N]

assert Sum(60) == 10
assert Sum(39) == 16
assert Sum(40) == 7

Write a python function to find sum of all prime divisors of a given number.


def is_triangleexists(a,b,c):
    if(a != 0 and b != 0 and c != 0 and (a + b + c)== 180):
        if((a + b)>= c or (b + c)>= a or (a + c)>= b):
            return True
        else:
            return False
    else:
        return False

Write a function to check if a triangle of positive area is possible with the given angles.


def Sum_of_Inverse_Divisors(N,Sum):
    ans = float(Sum)*1.0 /float(N);
    return round(ans,2);

assert Sum_of_Inverse_Divisors(6,12) == 2

assert Sum_of_Inverse_Divisors(9,13) == 1.44

assert Sum_of_Inverse_Divisors(1,4) == 4

Write a python function to find sum of inverse of divisors.


def remove_negs(num_list):
    for item in num_list:
        if item < 0:
           num_list.remove(item)
    return num_list

Write a python function to remove negative numbers from a list.


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

assert sum_of_odd_Factors(30) == 24
assert sum_of_odd_Factors(18) == 13
assert sum_of_odd_Factors(2) == 1

Write a python function to find sum of odd factors of a number.


import heapq as hq
def raw_heap(rawheap):
  hq.heapify(rawheap)
  return rawheap

Write a function which accepts an arbitrary list and converts it to a heap using heap queue algorithm.


def check_Even_Parity(x):
    parity = 0
    while (x != 0):
        x = x & (x - 1)
        parity += 1
    if (parity % 2 == 0):
        return True
    else:
        return False

assert check_Even_Parity(10) == True
assert check_Even_Parity(11) == False
assert check_Even_Parity(18) == True

Write a python function to check for even parity of a given number.


def find_Min_Swaps(arr,n) :
    noOfZeroes = [0] * n
    count = 0
    noOfZeroes[n - 1] = 1 - arr[n - 1]
    for i in range(n-2,-1,-1) :
        noOfZeroes[i] = noOfZeroes[i + 1]
        if (arr[i] == 0) :
            noOfZeroes[i] = noOfZeroes[i] + 1
    for i in range(0,n) :
        if (arr[i] == 1) :
            count = count + noOfZeroes[i]
    return count

Write a python function to find minimum adjacent swaps required to sort binary array.


def listify_list(list1):
  result = list(map(list,list1))
  return result

Write a function to list out the list of given strings individually using map function.


def count_list(input_list):
    return (len(input_list))**2

Write a function to count number of lists in a given list of lists and square the count.


from itertools import combinations
def sub_lists(my_list):
	subs = []
	for i in range(0, len(my_list)+1):
	  temp = [list(x) for x in combinations(my_list, i)]
	  if len(temp)>0:
	    subs.extend(temp)
	return subs

Write a function to generate all sublists of a given list.


import re
regex = '[a-zA-z0-9]$'
def check_alphanumeric(string):
	if(re.search(regex, string)):
		return ("Accept")
	else:
		return ("Discard")

assert check_alphanumeric("dawood@") == 'Discard'

assert check_alphanumeric("skdmsam326") == 'Accept'

assert check_alphanumeric("cooltricks@") == 'Discard'

Write a function to check whether the given string is ending with only alphanumeric characters or not using regex.


from collections import Counter
def anagram_lambda(texts,str):
  result = list(filter(lambda x: (Counter(str) == Counter(x)), texts))
  return result

assert anagram_lambda(["bcda", "abce", "cbda", "cbea", "adcb"],"abcd")==['bcda', 'cbda', 'adcb']

assert anagram_lambda(["recitals"," python"], "articles" )==["recitals"]

assert anagram_lambda([" keep"," abcdef"," xyz"]," peek")==[" keep"]

Write a function to find all anagrams of a string in a given list of strings using lambda function.


from collections import Counter
import re
def n_common_words(text,n):
  words = re.findall('\w+',text)
  n_common_words= Counter(words).most_common(n)
  return list(n_common_words)

assert n_common_words("python is a programming language",1)==[('python', 1)]

assert n_common_words("python is a programming language",5)==[('python', 1),('is', 1), ('a', 1), ('programming', 1), ('language', 1)]

Write a function to find the occurrences of n most common words in a given text.


def find_longest_conseq_subseq(arr, n):
	ans = 0
	count = 0
	arr.sort()
	v = []
	v.append(arr[0])
	for i in range(1, n):
		if (arr[i] != arr[i - 1]):
			v.append(arr[i])
	for i in range(len(v)):
		if (i > 0 and v[i] == v[i - 1] + 1):
			count += 1
		else:
			count = 1
		ans = max(ans, count)
	return ans

assert find_longest_conseq_subseq([1, 2, 2, 3], 4) == 3

assert find_longest_conseq_subseq([1, 9, 3, 10, 4, 20, 2], 7) == 4

Write a function to find the length of the longest sub-sequence such that elements in the subsequences are consecutive integers.


def palindrome_lambda(texts):
  result = list(filter(lambda x: (x == "".join(reversed(x))), texts))
  return result

assert palindrome_lambda(["php", "res", "Python", "abcd", "Java", "aaa"])==['php', 'aaa']

assert palindrome_lambda(["abcd", "Python", "abba", "aba"])==['abba', 'aba']

assert palindrome_lambda(["abcd", "abbccbba", "abba", "aba"])==['abbccbba', 'abba', 'aba']

Write a function to find palindromes in a given list of strings using lambda function.


def ntimes_list(nums,n):
    result = map(lambda x:n*x, nums)
    return list(result)

Write a function to print n-times a list using map function.


def check_monthnumb(monthname2):
  if(monthname2=="January" or monthname2=="March"or monthname2=="May" or monthname2=="July" or monthname2=="Augest" or monthname2=="October" or monthname2=="December"):
    return True
  else:
    return False

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


def min_Num(arr,n):
    odd = 0
    for i in range(n):
        if (arr[i] % 2):
            odd += 1
    if (odd % 2):
        return 1
    return 2

Write a python function to add a minimum number such that the sum of array becomes even.


def length_Of_Last_Word(a):
    l = 0
    x = a.strip()
    for i in range(len(x)):
        if x[i] == " ":
            l = 0
        else:
            l += 1
    return l

assert length_Of_Last_Word("python language") == 8

Write a python function to find the length of the last word in a given string.


def remove_list_range(list1, leftrange, rigthrange):
   result = [i for i in list1 if (min(i)>=leftrange and max(i)<=rigthrange)]
   return result

Write a function to remove sublists from a given list of lists, which are outside a given range.


def sum_positivenum(nums):
  sum_positivenum = list(filter(lambda nums:nums>0,nums))
  return sum(sum_positivenum)

Write a function to calculate the sum of the positive numbers of a given list of numbers using lambda function.


def are_Rotations(string1,string2):
    size1 = len(string1)
    size2 = len(string2)
    temp = ''
    if size1 != size2:
        return False
    temp = string1 + string1
    if (temp.count(string2)> 0):
        return True
    else:
        return False

assert are_Rotations("abc","cba") == False

assert are_Rotations("abcd","cdba") == False

assert are_Rotations("abacd","cdaba") == True

Write a python function to check whether the given strings are rotations of each other or not.


def check_subset(list1,list2):
    return all(map(list1.__contains__,list2))

Write a function to check if a nested list is a subset of another nested list.


def fibonacci(n):
  if n == 1 or n == 2:
    return 1
  else:
    return (fibonacci(n - 1) + (fibonacci(n - 2)))

assert fibonacci(7) == 13
assert fibonacci(8) == 21
assert fibonacci(9) == 34

Write a function to solve the fibonacci sequence using recursion.


def check_Concat(str1,str2):
    N = len(str1)
    M = len(str2)
    if (N % M != 0):
        return False
    for i in range(N):
        if (str1[i] != str2[i % M]):
            return False
    return True

assert check_Concat("abcabcabc","abc") == True

assert check_Concat("abcab","abc") == False

assert check_Concat("aba","ab") == False

Write a python function to check if the string is a concatenation of another string.


def min_difference(test_list):
  temp = [abs(b - a) for a, b in test_list]
  res = min(temp)
  return (res)

Write a function to find the minimum difference in the tuple pairs of given tuples.


def lcm(x, y):
   if x > y:
       z = x
   else:
       z = y
   while(True):
       if((z % x == 0) and (z % y == 0)):
           lcm = z
           break
       z += 1
   return lcm

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


def sort_String(str) :
    str = ''.join(sorted(str))
    return (str)

assert sort_String("cba") == "abc"
assert sort_String("data") == "aadt"
assert sort_String("zxy") == "xyz"

Write a python function to sort the given string.


def check_tuples(test_tuple, K):
  res = all(ele in K for ele in test_tuple)
  return (res)

Write a function to check if the given tuple contains only k elements.


import re
def text_match(text):
  patterns = 'a.*?b$'
  if re.search(patterns,  text):
    return ('Found a match!')
  else:
    return ('Not matched!')

assert text_match("aabbbbd") == 'Not matched!'

assert text_match("aabAbbbc") == 'Not matched!'

assert text_match("accddbbjjjb") == 'Found a match!'

Write a function that matches a string that has an 'a' followed by anything, ending in 'b' by using regex.


def Check_Solution(a,b,c) :
    if ((b*b) - (4*a*c)) > 0 :
        return ("2 solutions")
    elif ((b*b) - (4*a*c)) == 0 :
        return ("1 solution")
    else :
        return ("No solutions")

assert Check_Solution(2,5,2) == "2 solutions"

assert Check_Solution(1,1,1) == "No solutions"

assert Check_Solution(1,2,1) == "1 solution"

Write a python function to find number of solutions in quadratic equation.


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

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


def parallelogram_perimeter(b,h):
  perimeter=2*(b*h)
  return perimeter

Write a function to caluclate perimeter of a parallelogram.


def div_of_nums(nums,m,n):
 result = list(filter(lambda x: (x % m == 0 and x % n == 0), nums))
 return result

Write a function to find numbers divisible by m and n from a list of numbers using lambda function.


def all_Bits_Set_In_The_Given_Range(n,l,r):
    num = ((1 << r) - 1) ^ ((1 << (l - 1)) - 1)
    new_num = n & num
    if (num == new_num):
        return True
    return False

assert all_Bits_Set_In_The_Given_Range(10,2,1) == True

assert all_Bits_Set_In_The_Given_Range(5,2,4) == False

assert all_Bits_Set_In_The_Given_Range(22,2,3) == True

Write a python function to check whether all the bits are within a given range or not.


def is_Isomorphic(str1,str2):
    dict_str1 = {}
    dict_str2 = {}
    for i, value in enumerate(str1):
        dict_str1[value] = dict_str1.get(value,[]) + [i]
    for j, value in enumerate(str2):
        dict_str2[value] = dict_str2.get(value,[]) + [j]
    if sorted(dict_str1.values()) == sorted(dict_str2.values()):
        return True
    else:
        return False

assert is_Isomorphic("paper","title") == True

assert is_Isomorphic("ab","aa") == False

Write a python function to check whether the two given strings are isomorphic to each other or not.


def sum_num(numbers):
    total = 0
    for x in numbers:
        total += x
    return total/len(numbers)

Write a function to add all the numbers in a list and divide it with the length of the list.


def is_odd(n) :
    if (n^1 == n-1) :
        return True;
    else :
        return False;

assert is_odd(5) == True
assert is_odd(6) == False
assert is_odd(7) == True

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


def substract_elements(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 substract the elements of the given nested tuples.


def reverse_list_lists(lists):
    for l in lists:
        l.sort(reverse = True)
    return lists

Write a function to reverse each list in a given list of lists.


def find_Extra(arr1,arr2,n) :
    for i in range(0, n) :
        if (arr1[i] != arr2[i]) :
            return i
    return n

Write a python function to find the index of an extra element present in one sorted array.


def same_Length(A,B):
    while (A > 0 and B > 0):
        A = A / 10;
        B = B / 10;
    if (A == 0 and B == 0):
        return True;
    return False;

assert same_Length(12,1) == False
assert same_Length(2,2) == True
assert same_Length(10,20) == True

Write a python function to check whether the given two numbers have same number of digits or not.


import re
def remove_spaces(text):
 return (re.sub(' +',' ',text))

assert remove_spaces('python  program')==('python program')

assert remove_spaces('python   programming    language')==('python programming language')

Write a function to remove multiple spaces in a string.


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

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


def float_to_tuple(test_str):
  res = tuple(map(float, test_str.split(', ')))
  return (res)

Write a function to convert the given string of float type into tuple.


def max_sum_subseq(A):
    n = len(A)
    if n == 1:
        return A[0]
    look_up = [None] * n
    look_up[0] = A[0]
    look_up[1] = max(A[0], A[1])
    for i in range(2, n):
        look_up[i] = max(look_up[i - 1], look_up[i - 2] + A[i])
        look_up[i] = max(look_up[i], A[i])
    return look_up[n - 1]

Write a function to find the maximum sum of subsequences of given array with no adjacent elements.


def last(n):
   return n[-1]
def sort_list_last(tuples):
  return sorted(tuples, key=last)

Write a function to sort a list in increasing order by the last element in each tuple from a given list of non-empty tuples.


def is_Word_Present(sentence,word):
    s = sentence.split(" ")
    for i in s:
        if (i == word):
            return True
    return False

assert is_Word_Present("machine learning","machine") == True

assert is_Word_Present("easy","fun") == False

assert is_Word_Present("python language","code") == False

Write a python function to check whether the word is present in a given sentence or not.


from itertools import groupby
def extract_elements(numbers, n):
    result = [i for i, j in groupby(numbers) if len(list(j)) == n]
    return result

Write a function to extract specified number of elements from a given list, which follow each other continuously.


def check(arr,n):
    g = 0
    for i in range(1,n):
        if (arr[i] - arr[i - 1] > 0 and g == 1):
            return False
        if (arr[i] - arr[i] < 0):
            g = 1
    return True

Write a python function to check whether an array can be sorted or not by picking only the corner elements.


import re
def match_num(string):
    text = re.compile(r"^5")
    if text.match(string):
        return True
    else:
        return False

assert match_num('5-2345861')==True
assert match_num('6-2345861')==False
assert match_num('78910')==False

Write a function where a string will start with a specific number.


def smallest_multiple(n):
    if (n<=2):
      return n
    i = n * 2
    factors = [number  for number in range(n, 1, -1) if number * 2 > n]
    while True:
        for a in factors:
            if i % a != 0:
                i += n
                break
            if (a == factors[-1] and i % a == 0):
                return i

assert smallest_multiple(13)==360360
assert smallest_multiple(2)==2
assert smallest_multiple(1)==1

Write a function to find the smallest multiple of the first n numbers.


from collections import Counter
def add_dict(d1,d2):
   add_dict = Counter(d1) + Counter(d2)
   return add_dict

Write a function to combine two dictionaries by adding values for common keys.


def count_Unset_Bits(n) :
    cnt = 0;
    for i in range(1,n + 1) :
        temp = i;
        while (temp) :
            if (temp % 2 == 0) :
                cnt += 1;
            temp = temp // 2;
    return cnt;

assert count_Unset_Bits(2) == 1
assert count_Unset_Bits(5) == 4
assert count_Unset_Bits(14) == 17

Write a python function to count the total unset bits from 1 to n.


def even_num(x):
  if x%2==0:
     return True
  else:
    return False

assert even_num(13.5)==False
assert even_num(0)==True
assert even_num(-9)==False

Write a function to return true if the given number is even else return false.


def factorial(start,end):
    res = 1
    for i in range(start,end + 1):
        res *= i
    return res
def sum_of_square(n):
   return int(factorial(n + 1, 2 * n)  /factorial(1, n))

assert sum_of_square(4) == 70
assert sum_of_square(5) == 252
assert sum_of_square(2) == 6

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


import re
def extract_date(url):
        return re.findall(r'/(\d{4})/(\d{1,2})/(\d{1,2})/', url)

assert extract_date("https://www.washingtonpost.com/news/football-insider/wp/2016/09/02/odell-beckhams-fame-rests-on-one-stupid-little-ball-josh-norman-tells-author/") == [('2016', '09', '02')]

assert extract_date("https://www.indiatoday.in/movies/celebrities/story/wp/2020/11/03/odeof-sushant-singh-rajput-s-death-his-brother-in-law-shares-advice-for-fans-1749646/") == [('2020', '11', '03')]

assert extract_date("https://economictimes.indiatimes.com/news/economy/2020/12/29/finance/pension-assets-under-pfrda-touch-rs-5-32-lakh-crore/articleshow/79736619.cms") == [('2020', '12', '29')]

Write a function to extract year, month and date from a url by using regex.


def lucky_num(n):
 List=range(-1,n*n+9,2)
 i=2
 while List[i:]:List=sorted(set(List)-set(List[List[i]::List[i]]));i+=1
 return List[1:n+1]

Write a function to print the first n lucky numbers.


def find_fixed_point(arr, n):
	for i in range(n):
		if arr[i] is i:
			return i
	return -1

Write a function to find the fixed point in the given array.


def previous_palindrome(num):
    for x in range(num-1,0,-1):
        if str(x) == str(x)[::-1]:
            return x

assert previous_palindrome(99)==88
assert previous_palindrome(1221)==1111
assert previous_palindrome(120)==111

Write a function to find the previous palindrome of a specified number.


import datetime
def check_date(m, d, y):
    try:
        m, d, y = map(int, (m, d, y))
        datetime.date(y, m, d)
        return True
    except ValueError:
        return False

Write a function to validate a gregorian date.


def maximum_product(nums):
    import heapq
    a, b = heapq.nlargest(3, nums), heapq.nsmallest(2, nums)
    return max(a[0] * a[1] * a[2], a[0] * b[0] * b[1])

Write a function to compute maximum product of three numbers of a given array of integers using heap queue algorithm.


def binomial_coeff(n, k):
	C = [[0 for j in range(k + 1)]
			for i in range(n + 1)]
	for i in range(0, n + 1):
		for j in range(0, min(i, k) + 1):
			if (j == 0 or j == i):
				C[i][j] = 1
			else:
				C[i][j] = (C[i - 1][j - 1]
							+ C[i - 1][j])
	return C[n][k]
def lobb_num(n, m):
	return (((2 * m + 1) *
		binomial_coeff(2 * n, m + n))
					/ (m + n + 1))

assert int(lobb_num(5, 3)) == 35
assert int(lobb_num(3, 2)) == 5
assert int(lobb_num(4, 2)) == 20

Write a function to find ln, m lobb number.


import re
def end_num(string):
    text = re.compile(r".*[0-9]$")
    if text.match(string):
        return True
    else:
        return False

assert end_num('abcdef')==False
assert end_num('abcdef7')==True
assert end_num('abc')==False

Write a function to check for a number at the end of a string.


def is_Two_Alter(s):
    for i in range (len( s) - 2) :
        if (s[i] != s[i + 2]) :
            return False
    if (s[0] == s[1]):
        return False
    return True

assert is_Two_Alter("abab") == True
assert is_Two_Alter("aaaa") == False
assert is_Two_Alter("xyz") == False

Write a python function to check whether the given string is made up of two alternating characters or not.


def rearrange_numbs(array_nums):
  result = sorted(array_nums, key = lambda i: 0 if i == 0 else -1 / i)
  return result

Write a function to rearrange positive and negative numbers in a given array using lambda function.


def find_triplet_array(A, arr_size, sum):
	for i in range( 0, arr_size-2):
		for j in range(i + 1, arr_size-1):
			for k in range(j + 1, arr_size):
				if A[i] + A[j] + A[k] == sum:
					return  A[i],A[j],A[k]
					return True
	return False

Write a function to find if there is a triplet in the array whose sum is equal to a given value.


import re
def text_uppercase_lowercase(text):
        patterns = '[A-Z]+[a-z]+$'
        if re.search(patterns, text):
                return 'Found a match!'
        else:
                return ('Not matched!')

assert text_uppercase_lowercase("AaBbGg")==('Found a match!')

Write a function to find the sequences of one upper case letter followed by lower case letters.


def coin_change(S, m, n):
    table = [[0 for x in range(m)] for x in range(n+1)]
    for i in range(m):
        table[0][i] = 1
    for i in range(1, n+1):
        for j in range(m):
            x = table[i - S[j]][j] if i-S[j] >= 0 else 0
            y = table[i][j-1] if j >= 1 else 0
            table[i][j] = x + y
    return table[n][m-1]

Write a function to count coin change.


def multiply_list(items):
    tot = 1
    for x in items:
        tot *= x
    return tot

assert multiply_list([1,-2,3]) == -6
assert multiply_list([1,2,3,4]) == 24
assert multiply_list([3,1,2,3]) == 18

Write a python function to multiply all items in the list.


def remove_tuple(test_list):
  res = [sub for sub in test_list if not all(ele == None for ele in sub)]
  return (str(res))

Write a function to remove all tuples with all none values in the given tuple list.