Input: Write a function to find whether all the given tuples have equal length or not.

Answer:
def find_equal_tuple(Input, k):
  flag = 1
  for tuple in Input:
    if len(tuple) != k:
      flag = 0
      break
  return flag
def get_equal(Input, k):
  if find_equal_tuple(Input, k) == 1:
    return ("All tuples have same length")
  else:
    return ("All tuples do not have same length")

assert get_equal([(11, 22, 33), (44, 55, 66)], 3) == 'All tuples have same length'
assert get_equal([(1, 2, 3), (4, 5, 6, 7)], 3) == 'All tuples do not have same length'
assert get_equal([(1, 2), (3, 4)], 2) == 'All tuples have same length'


Input: Write a function to sort a list of elements using comb sort.

Answer:
def comb_sort(nums):
    shrink_fact = 1.3
    gaps = len(nums)
    swapped = True
    i = 0
    while gaps > 1 or swapped:
        gaps = int(float(gaps) / shrink_fact)
        swapped = False
        i = 0
        while gaps + i < len(nums):
            if nums[i] > nums[i+gaps]:
                nums[i], nums[i+gaps] = nums[i+gaps], nums[i]
                swapped = True
            i += 1
    return nums


Input: Write a python function to check whether the given number can be represented as difference of two squares or not.

Answer:
def dif_Square(n):
    if (n % 4 != 2):
        return True
    return False

assert dif_Square(5) == True
assert dif_Square(10) == False
assert dif_Square(15) == True


Input: Write a function to split the given string with multiple delimiters by using regex.

Answer:
import re
def multiple_split(text):
  return (re.split('; |, |\*|\n',text))

assert multiple_split('Forces of the \ndarkness*are coming into the play.') == ['Forces of the ', 'darkness', 'are coming into the play.']
assert multiple_split('Mi Box runs on the \n Latest android*which has google assistance and chromecast.') == ['Mi Box runs on the ', ' Latest android', 'which has google assistance and chromecast.']
assert multiple_split('Certain services\nare subjected to change*over the seperate subscriptions.') == ['Certain services', 'are subjected to change', 'over the seperate subscriptions.']


Input: Write a function to check whether it follows the sequence given in the patterns array.

Answer:
def is_samepatterns(colors, patterns):
    if len(colors) != len(patterns):
        return False
    sdict = {}
    pset = set()
    sset = set()
    for i in range(len(patterns)):
        pset.add(patterns[i])
        sset.add(colors[i])
        if patterns[i] not in sdict.keys():
            sdict[patterns[i]] = []

        keys = sdict[patterns[i]]
        keys.append(colors[i])
        sdict[patterns[i]] = keys

    if len(pset) != len(sset):
        return False

    for values in sdict.values():

        for i in range(len(values) - 1):
            if values[i] != values[i+1]:
                return False

    return True

assert is_samepatterns(["red","green","green"], ["a", "b", "b"])==True
assert is_samepatterns(["red","green","greenn"], ["a","b","b"])==False
assert is_samepatterns(["red","green","greenn"], ["a","b"])==False


Input: Write a function to find tuples which have all elements divisible by k from the given list of tuples.

Answer:
def find_tuples(test_list, K):
  res = [sub for sub in test_list if all(ele % K == 0 for ele in sub)]
  return (str(res))


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

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

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


Input: Write a python function to find the difference between sum of even and odd digits.

Answer:
def is_Diff(n):
    return (n % 11 == 0)

assert is_Diff (12345) == False
assert is_Diff(1212112) == True
assert is_Diff(1212) == False


Input: Write a python function to find number of integers with odd number of set bits.

Answer:
def count_With_Odd_SetBits(n):
    if (n % 2 != 0):
        return (n + 1) / 2
    count = bin(n).count('1')
    ans = n / 2
    if (count % 2 != 0):
        ans += 1
    return ans

assert count_With_Odd_SetBits(5) == 3
assert count_With_Odd_SetBits(10) == 5
assert count_With_Odd_SetBits(15) == 8


Input: Write a python function to check whether the length of the word is odd or not.

Answer:
def word_len(s):
    s = s.split(' ')
    for word in s:
        if len(word)%2!=0:
            return True
        else:
          return False

assert word_len("Hadoop") == False
assert word_len("great") == True
assert word_len("structure") == True


Input: Write a function to find the nth tetrahedral number.

Answer:
def tetrahedral_number(n):
	return (n * (n + 1) * (n + 2)) / 6

assert tetrahedral_number(5) == 35.0
assert tetrahedral_number(6) == 56.0
assert tetrahedral_number(7) == 84.0


Input: Write a function to zip the two given tuples.

Answer:
def zip_tuples(test_tup1, test_tup2):
  res = []
  for i, j in enumerate(test_tup1):
    res.append((j, test_tup2[i % len(test_tup2)]))
  return (res)


Input: Write a function to find the volume of a sphere.

Answer:
import math
def volume_sphere(r):
  volume=(4/3)*math.pi*r*r*r
  return volume


Input: Write a python function to find the character made by adding all the characters of the given string.

Answer:
def get_Char(strr):
    summ = 0
    for i in range(len(strr)):
        summ += (ord(strr[i]) - ord('a') + 1)
    if (summ % 26 == 0):
        return ord('z')
    else:
        summ = summ % 26
        return chr(ord('a') + summ - 1)

assert get_Char("abc") == "f"
assert get_Char("gfg") == "t"
assert get_Char("ab") == "c"


Input: Write a function to find the n-th number in newman conway sequence.

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

assert sequence(10) == 6
assert sequence(2) == 1
assert sequence(3) == 2


Input: Write a function to find the surface area of a sphere.

Answer:
import math
def surfacearea_sphere(r):
  surfacearea=4*math.pi*r*r
  return surfacearea


Input: Write a function to find nth centered hexagonal number.

Answer:
def centered_hexagonal_number(n):
  return 3 * n * (n - 1) + 1

assert centered_hexagonal_number(10) == 271
assert centered_hexagonal_number(2) == 7
assert centered_hexagonal_number(9) == 217


Input: Write a function to merge three dictionaries into a single expression.

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

assert merge_dictionaries_three({ "R": "Red", "B": "Black", "P": "Pink" }, { "G": "Green", "W": "White" },{ "O": "Orange", "W": "White", "B": "Black" })=={'B': 'Black', 'R': 'Red', 'P': 'Pink', 'G': 'Green', 'W': 'White', 'O': 'Orange'}
assert merge_dictionaries_three({ "R": "Red", "B": "Black", "P": "Pink" }, { "G": "Green", "W": "White" },{"L":"lavender","B":"Blue"})=={'W': 'White', 'P': 'Pink', 'B': 'Black', 'R': 'Red', 'G': 'Green', 'L': 'lavender'}
assert merge_dictionaries_three({ "R": "Red", "B": "Black", "P": "Pink" },{"L":"lavender","B":"Blue"},{ "G": "Green", "W": "White" })=={'B': 'Black', 'P': 'Pink', 'R': 'Red', 'G': 'Green', 'L': 'lavender', 'W': 'White'}


Input: Write a function to get the frequency of the elements in a list.

Answer:
import collections
def freq_count(list1):
  freq_count= collections.Counter(list1)
  return freq_count


Input: Write a function to find the closest smaller number than n.

Answer:
def closest_num(N):
  return (N - 1)

assert closest_num(11) == 10
assert closest_num(7) == 6
assert closest_num(12) == 11


Input: Write a python function to find the length of the longest word.

Answer:
def len_log(list1):
    max=len(list1[0])
    for i in list1:
        if len(i)>max:
            max=len(i)
    return max

assert len_log(["python","PHP","bigdata"]) == 7
assert len_log(["a","ab","abc"]) == 3
assert len_log(["small","big","tall"]) == 5


Input: Write a function to check if a substring is present in a given list of string values.

Answer:
def find_substring(str1, sub_str):
   if any(sub_str in s for s in str1):
       return True
   return False

assert find_substring(["red", "black", "white", "green", "orange"],"ack")==True
assert find_substring(["red", "black", "white", "green", "orange"],"abc")==False
assert find_substring(["red", "black", "white", "green", "orange"],"ange")==True


Input: Write a function to check whether the given number is undulating or not.

Answer:
def is_undulating(n):
	if (len(n) <= 2):
		return False
	for i in range(2, len(n)):
		if (n[i - 2] != n[i]):
			return False
	return True

assert is_undulating("1212121") == True
assert is_undulating("1991") == False
assert is_undulating("121") == True


Input: Write a function to calculate the value of 'a' to the power 'b'.

Answer:
def power(a,b):
	if b==0:
		return 1
	elif a==0:
		return 0
	elif b==1:
		return a
	else:
		return a*power(a,b-1)

assert power(3,4) == 81
assert power(2,3) == 8
assert power(5,5) == 3125


Input: Write a function to extract the index minimum value record from the given tuples.

Answer:
from operator import itemgetter
def index_minimum(test_list):
  res = min(test_list, key = itemgetter(1))[0]
  return (res)

assert index_minimum([('Rash', 143), ('Manjeet', 200), ('Varsha', 100)]) == 'Varsha'
assert index_minimum([('Yash', 185), ('Dawood', 125), ('Sanya', 175)]) == 'Dawood'
assert index_minimum([('Sai', 345), ('Salman', 145), ('Ayesha', 96)]) == 'Ayesha'


Input: Write a python function to find the minimum length of sublist.

Answer:
def Find_Min_Length(lst):
    minLength = min(len(x) for x in lst )
    return minLength


Input: Write a python function to find the number of divisors of a given integer.

Answer:
def divisor(n):
  for i in range(n):
    x = len([i for i in range(1,n+1) if not n % i])
  return x

assert divisor(15) == 4
assert divisor(12) == 6
assert divisor(9) == 3


Input: Write a function to find frequency count of list of lists.

Answer:
def frequency_lists(list1):
    list1 = [item for sublist in list1 for item in sublist]
    dic_data = {}
    for num in list1:
        if num in dic_data.keys():
            dic_data[num] += 1
        else:
            key = num
            value = 1
            dic_data[key] = value
    return dic_data


Input: Write a function to multiply all the numbers in a list and divide with the length of the list.

Answer:
def multiply_num(numbers):
    total = 1
    for x in numbers:
        total *= x
    return total/len(numbers)


Input: Write a function to convert the given decimal number to its binary equivalent.

Answer:
def decimal_to_binary(n):
    return bin(n).replace("0b","")

assert decimal_to_binary(8) == '1000'
assert decimal_to_binary(18) == '10010'
assert decimal_to_binary(7) == '111'


Input: Write a function to find the next smallest palindrome of a specified number.

Answer:
import sys
def next_smallest_palindrome(num):
    numstr = str(num)
    for i in range(num+1,sys.maxsize):
        if str(i) == str(i)[::-1]:
            return i

assert next_smallest_palindrome(99)==101
assert next_smallest_palindrome(1221)==1331
assert next_smallest_palindrome(120)==121


Input: Write a function to find the kth element in the given array.

Answer:
def kth_element(arr, n, k):
  for i in range(n):
    for j in range(0, n-i-1):
      if arr[j] > arr[j+1]:
        arr[j], arr[j+1] == arr[j+1], arr[j]
  return arr[k-1]


Input: Write a function to convert snake case string to camel case string.

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

assert snake_to_camel('python_program')=='PythonProgram'
assert snake_to_camel('python_language')==('PythonLanguage')
assert snake_to_camel('programming_language')==('ProgrammingLanguage')


Input: Write a function to find eulerian number a(n, m).

Answer:
def eulerian_num(n, m):
	if (m >= n or n == 0):
		return 0
	if (m == 0):
		return 1
	return ((n - m) * eulerian_num(n - 1, m - 1) +(m + 1) * eulerian_num(n - 1, m))

assert eulerian_num(3, 1) == 4
assert eulerian_num(4, 1) == 11
assert eulerian_num(5, 3) == 26


Input: Write a function to sort each sublist of strings in a given list of lists using lambda function.

Answer:
def sort_sublists(input_list):
    result = [sorted(x, key = lambda x:x[0]) for x in input_list]
    return result

assert sort_sublists((["green", "orange"], ["black", "white"], ["white", "black", "orange"]))==[['green', 'orange'], ['black', 'white'], ['black', 'orange', 'white']]
assert sort_sublists(([" red ","green" ],["blue "," black"],[" orange","brown"]))==[[' red ', 'green'], [' black', 'blue '], [' orange', 'brown']]
assert sort_sublists((["zilver","gold"], ["magnesium","aluminium"], ["steel", "bronze"]))==[['gold', 'zilver'],['aluminium', 'magnesium'], ['bronze', 'steel']]


Input: Write a python function to count true booleans in the given list.

Answer:
def count(lst):
    return sum(lst)

assert count([True,False,True]) == 2
assert count([False,False]) == 0
assert count([True,True,True]) == 3


Input: Write a function to add the given list to the given tuples.

Answer:
def add_lists(test_list, test_tup):
  res = tuple(list(test_tup) + test_list)
  return (res)


Input: Write a python function to count hexadecimal numbers for a given range.

Answer:
def count_Hexadecimal(L,R) :
    count = 0;
    for i in range(L,R + 1) :
        if (i >= 10 and i <= 15) :
            count += 1;
        elif (i > 15) :
            k = i;
            while (k != 0) :
                if (k % 16 >= 10) :
                    count += 1;
                k = k // 16;
    return count;

assert count_Hexadecimal(10,15) == 6
assert count_Hexadecimal(2,4) == 0
assert count_Hexadecimal(15,16) == 1


Input: Write a function to merge multiple sorted inputs into a single sorted iterator using heap queue algorithm.

Answer:
import heapq
def merge_sorted_list(num1,num2,num3):
  num1=sorted(num1)
  num2=sorted(num2)
  num3=sorted(num3)
  result = heapq.merge(num1,num2,num3)
  return list(result)


Input: Write a python function to find the count of rotations of a binary string with odd value.

Answer:
def odd_Equivalent(s,n):
    count=0
    for i in range(0,n):
        if (s[i] == '1'):
            count = count + 1
    return count

assert odd_Equivalent("011001",6) == 3
assert odd_Equivalent("11011",5) == 4
assert odd_Equivalent("1010",4) == 2


Input: Write a function to extract the ranges that are missing from the given list with the given start range and end range values.

Answer:
def extract_missing(test_list, strt_val, stop_val):
  res = []
  for sub in test_list:
    if sub[0] > strt_val:
      res.append((strt_val, sub[0]))
      strt_val = sub[1]
    if strt_val < stop_val:
      res.append((strt_val, stop_val))
  return (res)


Input: Write a function to find common elements in given nested lists. * list item * list item * list item * list item

Answer:
def common_in_nested_lists(nestedlist):
    result = list(set.intersection(*map(set, nestedlist)))
    return result


Input: Write a python function to find the perimeter of a cylinder.

Answer:
def perimeter(diameter,height) :
    return 2*(diameter+height)

assert perimeter(2,4) == 12
assert perimeter(1,2) == 6
assert perimeter(3,1) == 8


Input: Write a function to check if a string represents an integer or not.

Answer:
def check_integer(text):
 text = text.strip()
 if len(text) < 1:
    return None
 else:
     if all(text[i] in "0123456789" for i in range(len(text))):
          return True
     elif (text[0] in "+-") and \
         all(text[i] in "0123456789" for i in range(1,len(text))):
         return True
     else:
        return False

assert check_integer("python")==False
assert check_integer("1")==True
assert check_integer("12345")==True


Input: Write a function to assign frequency to each tuple in the given tuple list.

Answer:
from collections import Counter
def assign_freq(test_list):
  res = [(*key, val) for key, val in Counter(test_list).items()]
  return (str(res))


Input: Write a function to check whether all dictionaries in a list are empty or not.

Answer:
def empty_dit(list1):
 empty_dit=all(not d for d in list1)
 return empty_dit

assert empty_dit([{},{},{}])==True
assert empty_dit([{1,2},{},{}])==False
assert empty_dit({})==True


Input: Write a function to convert a given tuple of positive integers into an integer.

Answer:
def tuple_to_int(nums):
    result = int(''.join(map(str,nums)))
    return result

assert tuple_to_int((1,2,3))==123
assert tuple_to_int((4,5,6))==456
assert tuple_to_int((5,6,7))==567


Input: Write a function to convert all possible convertible elements in the list to float.

Answer:
def list_to_float(test_list):
  res = []
  for tup in test_list:
    temp = []
    for ele in tup:
      if ele.isalpha():
        temp.append(ele)
      else:
        temp.append(float(ele))
    res.append((temp[0],temp[1]))
  return (str(res))


Input: [link text](https:// [link text](https:// [link text](https://)))write a function to convert a string to a list.

Answer:
def string_to_list(string):
    lst = list(string.split(" "))
    return lst

assert string_to_list("python programming")==['python','programming']
assert string_to_list("lists tuples strings")==['lists','tuples','strings']
assert string_to_list("write a program")==['write','a','program']


Input: Write a python function to find the element that appears only once in a sorted array.

Answer:
def search(arr,n) :
    XOR = 0
    for i in range(n) :
        XOR = XOR ^ arr[i]
    return (XOR)


Input: Write a function to find the maximum product from the pairs of tuples within a given list.

Answer:
def max_product_tuple(list1):
    result_max = max([abs(x * y) for x, y in list1] )
    return result_max


Input: Write a function to find the triplet with sum of the given array

Answer:
def check_triplet(A, n, sum, count):
    if count == 3 and sum == 0:
        return True
    if count == 3 or n == 0 or sum < 0:
        return False
    return check_triplet(A, n - 1, sum - A[n - 1], count + 1) or\
           check_triplet(A, n - 1, sum, count)


Input: Write a function to find n’th smart number.

Answer:
MAX = 3000
def smartNumber(n):
	primes = [0] * MAX
	result = []
	for i in range(2, MAX):
		if (primes[i] == 0):
			primes[i] = 1
			j = i * 2
			while (j < MAX):
				primes[j] -= 1
				if ( (primes[j] + 3) == 0):
					result.append(j)
				j = j + i
	result.sort()
	return result[n - 1]

assert smartNumber(1) == 30
assert smartNumber(50) == 273
assert smartNumber(1000) == 2664


Input: Write a function to sum all amicable numbers from 1 to a specified number.

Answer:
def amicable_numbers_sum(limit):
    if not isinstance(limit, int):
        return "Input is not an integer!"
    if limit < 1:
        return "Input must be bigger than 0!"
    amicables = set()
    for num in range(2, limit+1):
        if num in amicables:
            continue
        sum_fact = sum([fact for fact in range(1, num) if num % fact == 0])
        sum_fact2 = sum([fact for fact in range(1, sum_fact) if sum_fact % fact == 0])
        if num == sum_fact2 and num != sum_fact:
            amicables.add(num)
            amicables.add(sum_fact2)
    return sum(amicables)

assert amicable_numbers_sum(999)==504
assert amicable_numbers_sum(9999)==31626
assert amicable_numbers_sum(99)==0


Input: Write a function to get the angle of a complex number.

Answer:
import cmath
def angle_complex(a,b):
  cn=complex(a,b)
  angle=cmath.phase(a+b)
  return angle


Input: Write a function to find the maximum difference between the number of 0s and number of 1s in any sub-string of the given binary string.

Answer:
def find_length(string, n):
	current_sum = 0
	max_sum = 0
	for i in range(n):
		current_sum += (1 if string[i] == '0' else -1)
		if current_sum < 0:
			current_sum = 0
		max_sum = max(current_sum, max_sum)
	return max_sum if max_sum else 0


Input: Write a python function to find the sum of common divisors of two given numbers.

Answer:
def sum(a,b):
    sum = 0
    for i in range (1,min(a,b)):
        if (a % i == 0 and b % i == 0):
            sum += i
    return sum


Input: Write a function to multiply two integers without using the * operator in python.

Answer:
def multiply_int(x, y):
    if y < 0:
        return -multiply_int(x, -y)
    elif y == 0:
        return 0
    elif y == 1:
        return x
    else:
        return x + multiply_int(x, y - 1)

assert multiply_int(10,20)==200
assert multiply_int(5,10)==50
assert multiply_int(4,8)==32


Input: Write a function to shortlist words that are longer than n from a given list of words.

Answer:
def long_words(n, str):
    word_len = []
    txt = str.split(" ")
    for x in txt:
        if len(x) > n:
            word_len.append(x)
    return word_len

assert long_words(3,"python is a programming language")==['python','programming','language']
assert long_words(2,"writing a program")==['writing','program']
assert long_words(5,"sorting list")==['sorting']


Input: Write a function to calculate magic square.

Answer:
def magic_square_test(my_matrix):
    iSize = len(my_matrix[0])
    sum_list = []
    sum_list.extend([sum (lines) for lines in my_matrix])
    for col in range(iSize):
        sum_list.append(sum(row[col] for row in my_matrix))
    result1 = 0
    for i in range(0,iSize):
        result1 +=my_matrix[i][i]
    sum_list.append(result1)
    result2 = 0
    for i in range(iSize-1,-1,-1):
        result2 +=my_matrix[i][i]
    sum_list.append(result2)
    if len(set(sum_list))>1:
        return False
    return True


Input: Write a function to find the item with maximum frequency in a given list.

Answer:
from collections import defaultdict
def max_occurrences(nums):
    dict = defaultdict(int)
    for i in nums:
        dict[i] += 1
    result = max(dict.items(), key=lambda x: x[1])
    return result


Input: Write a python function to reverse only the vowels of a given string.

Answer:
def reverse_vowels(str1):
	vowels = ""
	for char in str1:
		if char in "aeiouAEIOU":
			vowels += char
	result_string = ""
	for char in str1:
		if char in "aeiouAEIOU":
			result_string += vowels[-1]
			vowels = vowels[:-1]
		else:
			result_string += char
	return result_string

assert reverse_vowels("Python") == "Python"
assert reverse_vowels("USA") == "ASU"
assert reverse_vowels("ab") == "ab"


Input: Write a function to convert tuple to a string.

Answer:
def tup_string(tup1):
  str =  ''.join(tup1)
  return str


Input: Write a function to calculate the sum of the negative numbers of a given list of numbers using lambda function.

Answer:
def sum_negativenum(nums):
  sum_negativenum = list(filter(lambda nums:nums<0,nums))
  return sum(sum_negativenum)


Input: Write a python function to check whether the last element of given array is even or odd after performing an operation p times.

Answer:
def check_last (arr,n,p):
    _sum = 0
    for i in range(n):
        _sum = _sum + arr[i]
    if p == 1:
        if _sum % 2 == 0:
            return "ODD"
        else:
            return "EVEN"
    return "EVEN"

assert check_last([5,7,10],3,1) == "ODD"
assert check_last([2,3],2,3) == "EVEN"
assert check_last([1,2,3],3,1) == "ODD"


Input: Write a function to find the nth hexagonal number.

Answer:
def hexagonal_num(n):
	return n*(2*n - 1)

assert hexagonal_num(10) == 190
assert hexagonal_num(5) == 45
assert hexagonal_num(7) == 91


Input: Write a function to calculate electricity bill.

Answer:
def cal_electbill(units):
 if(units < 50):
    amount = units * 2.60
    surcharge = 25
 elif(units <= 100):
    amount = 130 + ((units - 50) * 3.25)
    surcharge = 35
 elif(units <= 200):
    amount = 130 + 162.50 + ((units - 100) * 5.26)
    surcharge = 45
 else:
    amount = 130 + 162.50 + 526 + ((units - 200) * 8.45)
    surcharge = 75
 total = amount + surcharge
 return total

assert cal_electbill(75)==246.25
assert cal_electbill(265)==1442.75
assert cal_electbill(100)==327.5


Input: Write a function to find the ration of zeroes in an array of integers.

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


Input: Write a python function to check whether the given number can be represented as sum of non-zero powers of 2 or not.

Answer:
def is_Sum_Of_Powers_Of_Two(n):
    if (n % 2 == 1):
        return False
    else:
        return True

assert is_Sum_Of_Powers_Of_Two(10) == True
assert is_Sum_Of_Powers_Of_Two(7) == False
assert is_Sum_Of_Powers_Of_Two(14) == True


Input: Write a function to find the circumference of a circle.

Answer:
def circle_circumference(r):
  perimeter=2*3.1415*r
  return perimeter

assert circle_circumference(10)==62.830000000000005
assert circle_circumference(5)==31.415000000000003
assert circle_circumference(4)==25.132


Input: Write a function to extract elements that occur singly in the given tuple list.

Answer:
def extract_singly(test_list):
  res = []
  temp = set()
  for inner in test_list:
    for ele in inner:
      if not ele in temp:
        temp.add(ele)
        res.append(ele)
  return (res)


Input: Write a function to sort a list of elements using pancake sort.

Answer:
def pancake_sort(nums):
    arr_len = len(nums)
    while arr_len > 1:
        mi = nums.index(max(nums[0:arr_len]))
        nums = nums[mi::-1] + nums[mi+1:len(nums)]
        nums = nums[arr_len-1::-1] + nums[arr_len:len(nums)]
        arr_len -= 1
    return nums


Input: Write a function to count the same pair in three given lists.

Answer:
def count_samepair(list1,list2,list3):
    result = sum(m == n == o for m, n, o in zip(list1,list2,list3))
    return result


Input: Write a function to find number of lists present in the given tuple.

Answer:
def find_lists(Input):
	if isinstance(Input, list):
		return 1
	else:
		return len(Input)


Input: Write a python function to find the sum of absolute differences in all pairs of the given array.

Answer:
def sum_Pairs(arr,n):
    sum = 0
    for i in range(n - 1,-1,-1):
        sum += i*arr[i] - (n-1-i) * arr[i]
    return sum


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

Answer:
def max_Abs_Diff(arr,n):
    minEle = arr[0]
    maxEle = arr[0]
    for i in range(1, n):
        minEle = min(minEle,arr[i])
        maxEle = max(maxEle,arr[i])
    return (maxEle - minEle)


Input: Write a function to find the ascii value of total characters in a string.

Answer:
def ascii_value_string(str1):
  for i in range(len(str1)):
   return ord(str1[i])

assert ascii_value_string("python")==112
assert ascii_value_string("Program")==80
assert ascii_value_string("Language")==76


Input: Write a function to find the maximum total path sum in the given triangle.

Answer:
def max_path_sum(tri, m, n):
	for i in range(m-1, -1, -1):
		for j in range(i+1):
			if (tri[i+1][j] > tri[i+1][j+1]):
				tri[i][j] += tri[i+1][j]
			else:
				tri[i][j] += tri[i+1][j+1]
	return tri[0][0]


Input: Write a function to divide a number into two parts such that the sum of digits is maximum.

Answer:
def sum_digits_single(x) :
    ans = 0
    while x :
        ans += x % 10
        x //= 10
    return ans
def closest(x) :
    ans = 0
    while (ans * 10 + 9 <= x) :
        ans = ans * 10 + 9
    return ans
def sum_digits_twoparts(N) :
    A = closest(N)
    return sum_digits_single(A) + sum_digits_single(N - A)

assert sum_digits_twoparts(35)==17
assert sum_digits_twoparts(7)==7
assert sum_digits_twoparts(100)==19


Input: Write a function to find the longest subsequence such that the difference between adjacents is one for the given array.

Answer:
def longest_subseq_with_diff_one(arr, n):
	dp = [1 for i in range(n)]
	for i in range(n):
		for j in range(i):
			if ((arr[i] == arr[j]+1) or (arr[i] == arr[j]-1)):
				dp[i] = max(dp[i], dp[j]+1)
	result = 1
	for i in range(n):
		if (result < dp[i]):
			result = dp[i]
	return result

assert longest_subseq_with_diff_one([1, 2, 3, 4, 5, 3, 2], 7) == 6
assert longest_subseq_with_diff_one([10, 9, 4, 5, 4, 8, 6], 7) == 3
assert longest_subseq_with_diff_one([1, 2, 3, 2, 3, 7, 2, 1], 8) == 7


Input: Write a python function to find whether the given number is present in the infinite sequence or not.

Answer:
def does_Contain_B(a,b,c):
    if (a == b):
        return True
    if ((b - a) * c > 0 and (b - a) % c == 0):
        return True
    return False

assert does_Contain_B(1,7,3) == True
assert does_Contain_B(1,-3,5) == False
assert does_Contain_B(3,2,5) == False


Input: Write a python function to check whether the given number is co-prime or not.

Answer:
def gcd(p,q):
    while q != 0:
        p, q = q,p%q
    return p
def is_coprime(x,y):
    return gcd(x,y) == 1

assert is_coprime(17,13) == True
assert is_coprime(15,21) == False
assert is_coprime(25,45) == False


Input: Write a function to sort the given array by using merge sort.

Answer:
def merge(a,b):
    c = []
    while len(a) != 0 and len(b) != 0:
        if a[0] < b[0]:
            c.append(a[0])
            a.remove(a[0])
        else:
            c.append(b[0])
            b.remove(b[0])
    if len(a) == 0:
        c += b
    else:
        c += a
    return c
def merge_sort(x):
    if len(x) == 0 or len(x) == 1:
        return x
    else:
        middle = len(x)//2
        a = merge_sort(x[:middle])
        b = merge_sort(x[middle:])
        return merge(a,b)


Input: Write a function to find the vertex of a parabola.

Answer:
def parabola_vertex(a, b, c):
  vertex=(((-b / (2 * a)),(((4 * a * c) - (b * b)) / (4 * a))))
  return vertex


Input: Write a function to extract every specified element from a given two dimensional list.

Answer:
def specified_element(nums, N):
    result = [i[N] for i in nums]
    return result


Input: Write a python function to toggle all even bits of a given number.

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

assert even_bit_toggle_number(10) == 0
assert even_bit_toggle_number(20) == 30
assert even_bit_toggle_number(30) == 20


Input: Write a function to convert a tuple of string values to a tuple of integer values.

Answer:
def tuple_int_str(tuple_str):
    result = tuple((int(x[0]), int(x[1])) for x in tuple_str)
    return result


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

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


Input: Write a python function to find k number of operations required to make all elements equal.

Answer:
def min_Ops(arr,n,k):
    max1 = max(arr)
    res = 0
    for i in range(0,n):
        if ((max1 - arr[i]) % k != 0):
            return -1
        else:
            res += (max1 - arr[i]) / k
    return int(res)


Input: Write a function to print the season for the given month and day.

Answer:
def month_season(month,days):
 if month in ('January', 'February', 'March'):
	 season = 'winter'
 elif month in ('April', 'May', 'June'):
	 season = 'spring'
 elif month in ('July', 'August', 'September'):
	 season = 'summer'
 else:
	 season = 'autumn'
 if (month == 'March') and (days > 19):
	 season = 'spring'
 elif (month == 'June') and (days > 20):
	 season = 'summer'
 elif (month == 'September') and (days > 21):
	 season = 'autumn'
 elif (month == 'October') and (days > 21):
	 season = 'autumn'
 elif (month == 'November') and (days > 21):
	 season = 'autumn'
 elif (month == 'December') and (days > 20):
	 season = 'winter'
 return season

assert month_season('January',4)==('winter')
assert month_season('October',28)==('autumn')
assert month_season('June',6)==('spring')


Input: Write a function to find x and y that satisfies ax + by = n.

Answer:
def solution (a, b, n):
	i = 0
	while i * a <= n:
		if (n - (i * a)) % b == 0:
			return ("x = ",i ,", y = ",
			int((n - (i * a)) / b))
			return 0
		i = i + 1
	return ("No solution")


Input: Write a function to remove all elements from a given list present in another list.

Answer:
def remove_elements(list1, list2):
    result = [x for x in list1 if x not in list2]
    return result


Input: Write a function to calculate the sum of the positive integers of n+(n-2)+(n-4)... (until n-x =< 0).

Answer:
def sum_series(n):
  if n < 1:
    return 0
  else:
    return n + sum_series(n - 2)

assert sum_series(6)==12
assert sum_series(10)==30
assert sum_series(9)==25


Input: Write a function to calculate the area of a regular polygon.

Answer:
from math import tan, pi
def area_polygon(s,l):
  area = s * (l ** 2) / (4 * tan(pi / s))
  return area


Input: Write a python function to check whether the sum of divisors are same or not.

Answer:
import math
def divSum(n):
    sum = 1;
    i = 2;
    while(i * i <= n):
        if (n % i == 0):
            sum = (sum + i +math.floor(n / i));
        i += 1;
    return sum;
def areEquivalent(num1,num2):
    return divSum(num1) == divSum(num2);

assert areEquivalent(36,57) == False
assert areEquivalent(2,4) == False
assert areEquivalent(23,47) == True


Input: Write a python function to count characters at same position in a given string (lower and uppercase characters) as in english alphabet.

Answer:
def count_char_position(str1):
    count_chars = 0
    for i in range(len(str1)):
        if ((i == ord(str1[i]) - ord('A')) or
            (i == ord(str1[i]) - ord('a'))):
            count_chars += 1
    return count_chars

assert count_char_position("xbcefg") == 2
assert count_char_position("ABcED") == 3
assert count_char_position("AbgdeF") == 5


Input: Write a python function to count the pairs with xor as an even number.

Answer:
def find_even_Pair(A,N):
    evenPair = 0
    for i in range(0,N):
        for j in range(i+1,N):
            if ((A[i] ^ A[j]) % 2 == 0):
                evenPair+=1
    return evenPair;


Input: Write a python function to find smallest power of 2 greater than or equal to n.

Answer:
def next_Power_Of_2(n):
    count = 0;
    if (n and not(n & (n - 1))):
        return n
    while( n != 0):
        n >>= 1
        count += 1
    return 1 << count;

assert next_Power_Of_2(0) == 1
assert next_Power_Of_2(5) == 8
assert next_Power_Of_2(17) == 32


Input: Write a python function to find the frequency of a number in a given array.

Answer:
def frequency(a,x):
    count = 0
    for i in a:
        if i == x: count += 1
    return count


Input: Write a function to calculate the nth pell number.

Answer:
def get_pell(n):
	if (n <= 2):
		return n
	a = 1
	b = 2
	for i in range(3, n+1):
		c = 2 * b + a
		a = b
		b = c
	return b

assert get_pell(4) == 12
assert get_pell(7) == 169
assert get_pell(8) == 408


Input: Write a function to find sum of the numbers in a list between the indices of a specified range.

Answer:
def sum_range_list(list1, m, n):
    sum_range = 0
    for i in range(m, n+1, 1):
        sum_range += list1[i]
    return sum_range


Input: Write a function to find the perimeter of a pentagon.

Answer:
import math
def perimeter_pentagon(a):
  perimeter=(5*a)
  return perimeter

assert perimeter_pentagon(5)==25
assert perimeter_pentagon(10)==50
assert perimeter_pentagon(15)==75


Input: Write a function to find the occurence of characters 'std' in the given string 1. list item 1. list item 1. list item 2. list item 2. list item 2. list item

Answer:
def count_occurance(s):
  count=0
  for i in range(len(s)):
    if (s[i]== 's' and s[i+1]=='t' and s[i+2]== 'd'):
      count = count + 1
  return count

assert count_occurance("letstdlenstdporstd") == 3
assert count_occurance("truststdsolensporsd") == 1
assert count_occurance("makestdsostdworthit") == 2


Input: Write a function to remove everything except alphanumeric characters from a string.

Answer:
import re
def remove_splchar(text):
 pattern = re.compile('[\W_]+')
 return (pattern.sub('', text))

assert remove_splchar('python  @#&^%$*program123')==('pythonprogram123')
assert remove_splchar('python %^$@!^&*()  programming24%$^^()    language')==('pythonprogramming24language')
assert remove_splchar('python   ^%&^()(+_)(_^&67)                  program')==('python67program')


Input: Write a function to group a sequence of key-value pairs into a dictionary of lists.

Answer:
def group_keyvalue(l):
    result = {}
    for k, v in l:
         result.setdefault(k, []).append(v)
    return result


Input: Write a function to verify validity of a string of parentheses.

Answer:
def is_valid_parenthese( str1):
        stack, pchar = [], {"(": ")", "{": "}", "[": "]"}
        for parenthese in str1:
            if parenthese in pchar:
                stack.append(parenthese)
            elif len(stack) == 0 or pchar[stack.pop()] != parenthese:
                return False
        return len(stack) == 0

assert is_valid_parenthese("(){}[]")==True
assert is_valid_parenthese("()[{)}")==False
assert is_valid_parenthese("()")==True


Input: Write a function to find the perimeter of a triangle.

Answer:
def perimeter_triangle(a,b,c):
  perimeter=a+b+c
  return perimeter

assert perimeter_triangle(10,20,30)==60
assert perimeter_triangle(3,4,5)==12
assert perimeter_triangle(25,35,45)==105


Input: Write a python function to find two distinct numbers such that their lcm lies within the given range.

Answer:
def answer(L,R):
    if (2 * L <= R):
        return (L ,2*L)
    else:
        return (-1)

assert answer(3,8) == (3,6)
assert answer(2,6) == (2,4)
assert answer(1,3) == (1,2)


Input: Write a function to search some literals strings in a string.

Answer:
import re
def string_literals(patterns,text):
  for pattern in patterns:
     if re.search(pattern,  text):
       return ('Matched!')
     else:
       return ('Not Matched!')

assert string_literals(['language'],'python language')==('Matched!')
assert string_literals(['program'],'python language')==('Not Matched!')
assert string_literals(['python'],'programming language')==('Not Matched!')


Input: Write a function to find if the given number is a keith number or not.

Answer:
def is_num_keith(x):
	terms = []
	temp = x
	n = 0
	while (temp > 0):
		terms.append(temp % 10)
		temp = int(temp / 10)
		n+=1
	terms.reverse()
	next_term = 0
	i = n
	while (next_term < x):
		next_term = 0
		for j in range(1,n+1):
			next_term += terms[i - j]
		terms.append(next_term)
		i+=1
	return (next_term == x)

assert is_num_keith(14) == True
assert is_num_keith(12) == False
assert is_num_keith(197) == True


Input: Write a function to calculate distance between two points using latitude and longitude.

Answer:
from math import radians, sin, cos, acos
def distance_lat_long(slat,slon,elat,elon):
 dist = 6371.01 * acos(sin(slat)*sin(elat) + cos(slat)*cos(elat)*cos(slon - elon))
 return dist


Input: Write a function to find the longest common prefix in the given set of strings.

Answer:
def common_prefix_util(str1, str2):
	result = "";
	n1 = len(str1)
	n2 = len(str2)
	i = 0
	j = 0
	while i <= n1 - 1 and j <= n2 - 1:
		if (str1[i] != str2[j]):
			break
		result += str1[i]
		i += 1
		j += 1
	return (result)
def common_prefix (arr, n):
	prefix = arr[0]
	for i in range (1, n):
		prefix = common_prefix_util(prefix, arr[i])
	return (prefix)

assert common_prefix(["tablets", "tables", "taxi", "tamarind"], 4) == 'ta'
assert common_prefix(["apples", "ape", "april"], 3) == 'ap'
assert common_prefix(["teens", "teenager", "teenmar"], 3) == 'teen'


Input: Write a function to find uppercase, lowercase, special character and numeric values using regex.

Answer:
import re
def find_character(string):
  uppercase_characters = re.findall(r"[A-Z]", string)
  lowercase_characters = re.findall(r"[a-z]", string)
  numerical_characters = re.findall(r"[0-9]", string)
  special_characters = re.findall(r"[, .!?]", string)
  return uppercase_characters, lowercase_characters, numerical_characters, special_characters


Input: Write a function to count all the distinct pairs having a difference of k in any array.

Answer:
def count_pairs(arr, n, k):
  count=0;
  for i in range(0,n):
    for j in range(i+1, n):
      if arr[i] - arr[j] == k or arr[j] - arr[i] == k:
        count += 1
  return count


Input: Write a function to find all the values in a list that are greater than a specified number.

Answer:
def greater_specificnum(list,num):
 greater_specificnum=all(x >= num for x in list)
 return greater_specificnum

assert greater_specificnum([220, 330, 500],200)==True
assert greater_specificnum([12, 17, 21],20)==False
assert greater_specificnum([1,2,3,4],10)==False


Input: Write a function to find the focus of a parabola.

Answer:
def parabola_focus(a, b, c):
  focus= (((-b / (2 * a)),(((4 * a * c) - (b * b) + 1) / (4 * a))))
  return focus


Input: Write a function to search some literals strings in a string by using regex.

Answer:
import re
def check_literals(text, patterns):
  for pattern in patterns:
    if re.search(pattern,  text):
        return ('Matched!')
    else:
        return ('Not Matched!')

assert check_literals('The quick brown fox jumps over the lazy dog.',['fox']) == 'Matched!'
assert check_literals('The quick brown fox jumps over the lazy dog.',['horse']) == 'Not Matched!'
assert check_literals('The quick brown fox jumps over the lazy dog.',['lazy']) == 'Matched!'


Input: Write a function to find the longest common subsequence for the given two sequences.

Answer:
def longest_common_subsequence(X, Y, m, n):
    if m == 0 or n == 0:
       return 0
    elif X[m-1] == Y[n-1]:
       return 1 + longest_common_subsequence(X, Y, m-1, n-1)
    else:
       return max(longest_common_subsequence(X, Y, m, n-1), longest_common_subsequence(X, Y, m-1, n))

assert longest_common_subsequence("AGGTAB" , "GXTXAYB", 6, 7) == 4
assert longest_common_subsequence("ABCDGH" , "AEDFHR", 6, 6) == 3
assert longest_common_subsequence("AXYT" , "AYZX", 4, 4) == 2


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

Answer:
def prod_Square(n):
    for i in range(2,(n) + 1):
        if (i*i < (n+1)):
            for j in range(2,n + 1):
                if ((i*i*j*j) == n):
                    return True;
    return False;

assert prod_Square(25) == False
assert prod_Square(30) == False
assert prod_Square(16) == True


Input: Write a python function to find the first missing positive number.

Answer:
def first_Missing_Positive(arr,n):
    ptr = 0
    for i in range(n):
        if arr[i] == 1:
            ptr = 1
            break
    if ptr == 0:
        return(1)
    for i in range(n):
        if arr[i] <= 0 or arr[i] > n:
            arr[i] = 1
    for i in range(n):
        arr[(arr[i] - 1) % n] += n
    for i in range(n):
        if arr[i] <= n:
            return(i + 1)
    return(n + 1)

assert first_Missing_Positive([1,2,3,-1,5],5) == 4
assert first_Missing_Positive([0,-1,-2,1,5,8],6) == 2
assert first_Missing_Positive([0,1,2,5,-8],5) == 3


Input: Write a python function to count the number of integral co-ordinates that lie inside a square.

Answer:
def count_Intgral_Points(x1,y1,x2,y2):
    return ((y2 - y1 - 1) * (x2 - x1 - 1))

assert count_Intgral_Points(1,1,4,4) == 4
assert count_Intgral_Points(1,2,1,2) == 1
assert count_Intgral_Points(4,2,6,4) == 1


Input: Write a function to check whether the given month name contains 30 days or not.

Answer:
def check_monthnumber(monthname3):
  if monthname3 =="April" or monthname3== "June" or monthname3== "September" or monthname3== "November":
    return True
  else:
    return False

assert check_monthnumber("February")==False
assert check_monthnumber("June")==True
assert check_monthnumber("April")==True


Input: Write a python function to check whether a string has atleast one letter and one number.

Answer:
def check_String(str):
    flag_l = False
    flag_n = False
    for i in str:
        if i.isalpha():
            flag_l = True
        if i.isdigit():
            flag_n = True
    return flag_l and flag_n

assert check_String('thishasboth29') == True
assert check_String('python') == False
assert check_String ('string') == False


Input: Write a function to remove the duplicates from the given tuple.

Answer:
def remove_tuple(test_tup):
  res = tuple(set(test_tup))
  return (res)


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

Answer:
def octal_To_Decimal(n):
    num = n;
    dec_value = 0;
    base = 1;
    temp = num;
    while (temp):
        last_digit = temp % 10;
        temp = int(temp / 10);
        dec_value += last_digit*base;
        base = base * 8;
    return dec_value;

assert octal_To_Decimal(25) == 21
assert octal_To_Decimal(30) == 24
assert octal_To_Decimal(40) == 32


Input: Write a python function to find the first position of an element in a sorted array.

Answer:
def first(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
            high = mid - 1
    return res


Input: Write a function to remove all the tuples with length k.

Answer:
def remove_tuples(test_list, K):
  res = [ele for ele in test_list if len(ele) != K]
  return (res)


Input: Write a function to perform the exponentiation of the given two tuples.

Answer:
def find_exponentio(test_tup1, test_tup2):
  res = tuple(ele1 ** ele2 for ele1, ele2 in zip(test_tup1, test_tup2))
  return (res)


Input: Write a function to find the largest triangle that can be inscribed in an ellipse.

Answer:
import math
def largest_triangle(a,b):
    if (a < 0 or b < 0):
        return -1
    area = (3 * math.sqrt(3) * pow(a, 2)) / (4 * b);
    return area


Input: Write a python function to find highest power of 2 less than or equal to given number.

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

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


Input: Write a function to find all index positions of the maximum values in a given list.

Answer:
def position_max(list1):
    max_val = max(list1)
    max_result = [i for i, j in enumerate(list1) if j == max_val]
    return max_result


Input: Write a python function to check whether the elements in a list are same or not.

Answer:
def chkList(lst):
    return len(set(lst)) == 1

assert chkList(['one','one','one']) == True
assert chkList(['one','Two','Three']) == False
assert chkList(['bigdata','python','Django']) == False


Input: Write a function to remove even characters in a string.

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

assert remove_even("python")==("pto")
assert remove_even("program")==("porm")
assert remove_even("language")==("lnug")


Input: Write a python function to find the hamming distance between given two integers.

Answer:
def hamming_Distance(n1,n2) :
    x = n1 ^ n2
    setBits = 0
    while (x > 0) :
        setBits += x & 1
        x >>= 1
    return setBits

assert hamming_Distance(4,8) == 2
assert hamming_Distance(2,4) == 2
assert hamming_Distance(1,2) == 2


Input: Write a python function to count the occurrence of a given character in a string.

Answer:
def count(s,c) :
    res = 0
    for i in range(len(s)) :
        if (s[i] == c):
            res = res + 1
    return res

assert count("abcc","c") == 2
assert count("ababca","a") == 3
assert count("mnmm0pm","m") == 4


Input: Write a function to find the inversions of tuple elements in the given tuple list.

Answer:
def inversion_elements(test_tup):
  res = tuple(list(map(lambda x: ~x, list(test_tup))))
  return (res)


Input: Write a function to perform the adjacent element concatenation in the given tuples.

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

assert concatenate_elements(("DSP ", "IS ", "BEST ", "FOR ", "ALL ", "UTS")) == ('DSP IS ', 'IS BEST ', 'BEST FOR ', 'FOR ALL ', 'ALL UTS')
assert concatenate_elements(("RES ", "IS ", "BEST ", "FOR ", "ALL ", "QESR")) == ('RES IS ', 'IS BEST ', 'BEST FOR ', 'FOR ALL ', 'ALL QESR')
assert concatenate_elements(("MSAM", "IS ", "BEST ", "FOR ", "ALL ", "SKD")) == ('MSAMIS ', 'IS BEST ', 'BEST FOR ', 'FOR ALL ', 'ALL SKD')


Input: Write a function to count the longest repeating subsequences such that the two subsequences don’t have same string characters at same positions.

Answer:
def find_longest_repeating_subseq(str):
	n = len(str)
	dp = [[0 for k in range(n+1)] for l in range(n+1)]
	for i in range(1, n+1):
		for j in range(1, n+1):
			if (str[i-1] == str[j-1] and i != j):
				dp[i][j] = 1 + dp[i-1][j-1]
			else:
				dp[i][j] = max(dp[i][j-1], dp[i-1][j])
	return dp[n][n]

assert find_longest_repeating_subseq("AABEBCDD") == 3
assert find_longest_repeating_subseq("aabb") == 2
assert find_longest_repeating_subseq("aab") == 1


Input: Write a function to check the given decimal with a precision of 2 by using regex.

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

assert is_decimal('123.11') == True
assert is_decimal('0.21') == True
assert is_decimal('123.1214') == False


Input: Write a function to delete the smallest element from the given heap and then insert a new item.

Answer:
import heapq as hq
def heap_replace(heap,a):
  hq.heapify(heap)
  hq.heapreplace(heap, a)
  return heap


Input: Write a function to check that the given string contains only a certain set of characters(in this case a-z, a-z and 0-9) by using regex.

Answer:
import re
def is_allowed_specific_char(string):
    get_char = re.compile(r'[^a-zA-Z0-9.]')
    string = get_char.search(string)
    return not bool(string)

assert is_allowed_specific_char("ABCDEFabcdef123450") == True
assert is_allowed_specific_char("*&%@#!}{") == False
assert is_allowed_specific_char("HELLOhowareyou98765") == True


Input: Write a python function to count numbers whose oth and nth bits are set.

Answer:
def count_Num(n):
    if (n == 1):
        return 1
    count = pow(2,n - 2)
    return count

assert count_Num(2) == 1
assert count_Num(3) == 2
assert count_Num(1) == 1


Input: Write a python function to find the sum of fourth power of n natural numbers.

Answer:
import math
def fourth_Power_Sum(n):
    sum = 0
    for i in range(1,n+1) :
        sum = sum + (i*i*i*i)
    return sum

assert fourth_Power_Sum(2) == 17
assert fourth_Power_Sum(4) == 354
assert fourth_Power_Sum(6) == 2275


Input: Write a function to perform the concatenation of two string tuples.

Answer:
def concatenate_strings(test_tup1, test_tup2):
  res = tuple(ele1 + ele2 for ele1, ele2 in zip(test_tup1, test_tup2))
  return (res)

assert concatenate_strings(("Manjeet", "Nikhil", "Akshat"), (" Singh", " Meherwal", " Garg")) == ('Manjeet Singh', 'Nikhil Meherwal', 'Akshat Garg')
assert concatenate_strings(("Shaik", "Ayesha", "Sanya"), (" Dawood", " Begum", " Singh")) == ('Shaik Dawood', 'Ayesha Begum', 'Sanya Singh')
assert concatenate_strings(("Harpreet", "Priyanka", "Muskan"), ("Kour", " Agarwal", "Sethi")) == ('HarpreetKour', 'Priyanka Agarwal', 'MuskanSethi')


Input: Write a function to convert radians to degrees.

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


Input: Write a function to decode a run-length encoded given list.

Answer:
def decode_list(alist):
    def aux(g):
        if isinstance(g, list):
            return [(g[1], range(g[0]))]
        else:
            return [(g, [0])]
    return [x for g in alist for x, R in aux(g) for i in R]


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

Answer:
def check_subset_list(list1, list2):
    l1, l2 = list1[0], list2[0]
    exist = True
    for i in list2:
        if i not in list1:
            exist = False
    return exist


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

Answer:
def first_Repeated_Char(str):
    h = {}
    for ch in str:
        if ch in h:
            return ch;
        else:
            h[ch] = 0
    return '\0'

assert first_Repeated_Char("Google") == "o"
assert first_Repeated_Char("data") == "a"
assert first_Repeated_Char("python") == '\0'


Input: Write a python function to find the minimum operations required to make two numbers equal.

Answer:
import math
def min_Operations(A,B):
    if (A > B):
        swap(A,B)
    B = B // math.gcd(A,B);
    return B - 1

assert min_Operations(2,4) == 1
assert min_Operations(4,10) == 4
assert min_Operations(1,4) == 3


Input: Write a function to extract maximum and minimum k elements in the given tuple.

Answer:
def extract_min_max(test_tup, K):
  res = []
  test_tup = list(test_tup)
  temp = sorted(test_tup)
  for idx, val in enumerate(temp):
    if idx < K or idx >= len(temp) - K:
      res.append(val)
  res = tuple(res)
  return (res)


Input: Write a function to replace maximum n occurrences of spaces, commas, or dots with a colon.

Answer:
import re
def replace_max_specialchar(text,n):
 return (re.sub("[ ,.]", ":", text, n))

assert replace_max_specialchar('Python language, Programming language.',2)==('Python:language: Programming language.')
assert replace_max_specialchar('a b c,d e f',3)==('a:b:c:d e f')
assert replace_max_specialchar('ram reshma,ram rahim',1)==('ram:reshma,ram rahim')


Input: Write a python function to find the first even number in a given list of numbers.

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


Input: Write a function to check if all the elements in tuple have same data type or not.

Answer:
def check_type(test_tuple):
  res = True
  for ele in test_tuple:
    if not isinstance(ele, type(test_tuple[0])):
      res = False
      break
  return (res)

assert check_type((5, 6, 7, 3, 5, 6) ) == True
assert check_type((1, 2, "4") ) == False
assert check_type((3, 2, 1, 4, 5) ) == True


Input: Write a function to check for majority element in the given sorted array.

Answer:
def is_majority(arr, n, x):
	i = binary_search(arr, 0, n-1, x)
	if i == -1:
		return False
	if ((i + n//2) <= (n -1)) and arr[i + n//2] == x:
		return True
	else:
		return False
def binary_search(arr, low, high, x):
	if high >= low:
		mid = (low + high)//2
		if (mid == 0 or x > arr[mid-1]) and (arr[mid] == x):
			return mid
		elif x > arr[mid]:
			return binary_search(arr, (mid + 1), high, x)
		else:
			return binary_search(arr, low, (mid -1), x)
	return -1


Input: Write a python function to count set bits of a given number.

Answer:
def count_Set_Bits(n):
    count = 0
    while (n):
        count += n & 1
        n >>= 1
    return count

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


Input: Write a python function to find the minimum element in a sorted and rotated array.

Answer:
def find_Min(arr,low,high):
    while (low < high):
        mid = low + (high - low) // 2;
        if (arr[mid] == arr[high]):
            high -= 1;
        elif (arr[mid] > arr[high]):
            low = mid + 1;
        else:
            high = mid;
    return arr[high];


Input: Write a python function to remove the characters which have odd index values of a given string.

Answer:
def odd_values_string(str):
  result = ""
  for i in range(len(str)):
    if i % 2 == 0:
      result = result + str[i]
  return result

assert odd_values_string('abcdef') == 'ace'
assert odd_values_string('python') == 'pto'
assert odd_values_string('data') == 'dt'


Input: Write a function to find minimum of three numbers.

Answer:
def min_of_three(a,b,c):
      if (a <= b) and (a <= c):
        smallest = a
      elif (b <= a) and (b <= c):
        smallest = b
      else:
        smallest = c
      return smallest


Input: Write a python function to check whether all the bits are unset in the given range or not.

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

assert all_Bits_Set_In_The_Given_Range(4,1,2) == True
assert all_Bits_Set_In_The_Given_Range(17,2,4) == True
assert all_Bits_Set_In_The_Given_Range(39,4,6) == False


Input: Write a function to re-arrange the elements of the given array so that all negative elements appear before positive ones.

Answer:
def re_arrange_array(arr, n):
  j=0
  for i in range(0, n):
    if (arr[i] < 0):
      temp = arr[i]
      arr[i] = arr[j]
      arr[j] = temp
      j = j + 1
  return arr


Input: Write a function to replace blank spaces with any character in a string.

Answer:
def replace_blank(str1,char):
 str2 = str1.replace(' ', char)
 return str2

assert replace_blank("hello people",'@')==("hello@people")
assert replace_blank("python program language",'$')==("python$program$language")
assert replace_blank("blank space","-")==("blank-space")


Input: Write a function to find the maximum sum in the given right triangle of numbers.

Answer:
def max_sum(tri, n):
	if n > 1:
		tri[1][1] = tri[1][1]+tri[0][0]
		tri[1][0] = tri[1][0]+tri[0][0]
	for i in range(2, n):
		tri[i][0] = tri[i][0] + tri[i-1][0]
		tri[i][i] = tri[i][i] + tri[i-1][i-1]
		for j in range(1, i):
			if tri[i][j]+tri[i-1][j-1] >= tri[i][j]+tri[i-1][j]:
				tri[i][j] = tri[i][j] + tri[i-1][j-1]
			else:
				tri[i][j] = tri[i][j]+tri[i-1][j]
	return (max(tri[n-1]))


Input: Write a function to get the n largest items from a dataset.

Answer:
import heapq
def larg_nnum(list1,n):
 largest=heapq.nlargest(n,list1)
 return largest


Input: Write a function to find the lateral surface area of a cylinder.

Answer:
def lateralsuface_cylinder(r,h):
  lateralsurface= 2*3.1415*r*h
  return lateralsurface

assert lateralsuface_cylinder(10,5)==314.15000000000003
assert lateralsuface_cylinder(4,5)==125.66000000000001
assert lateralsuface_cylinder(4,10)==251.32000000000002


Input: Write a function to find the volume of a cube.

Answer:
def volume_cube(l):
  volume = l * l * l
  return volume

assert volume_cube(3)==27
assert volume_cube(2)==8
assert volume_cube(5)==125


Input: Write a python function to set all even bits of a given number.

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

assert even_bit_set_number(10) == 10
assert even_bit_set_number(20) == 30
assert even_bit_set_number(30) == 30


Input: Write a python function to count the maximum number of equilateral triangles that can be formed within a given equilateral triangle.

Answer:
def No_of_Triangle(N,K):
    if (N < K):
        return -1;
    else:
        Tri_up = 0;
        Tri_up = ((N - K + 1) *(N - K + 2)) // 2;
        Tri_down = 0;
        Tri_down = ((N - 2 * K + 1) *(N - 2 * K + 2)) // 2;
        return Tri_up + Tri_down;

assert No_of_Triangle(4,2) == 7
assert No_of_Triangle(4,3) == 3
assert No_of_Triangle(1,3) == -1


Input: Write a function to check the occurrences of records which occur similar times in the given tuples.

Answer:
from collections import Counter
def check_occurences(test_list):
  res = dict(Counter(tuple(ele) for ele in map(sorted, test_list)))
  return  (res)


Input: Write a python function to count number of non-empty substrings of a given string.

Answer:
def number_of_substrings(str):
	str_len = len(str);
	return int(str_len * (str_len + 1) / 2);

assert number_of_substrings("abc") == 6
assert number_of_substrings("abcd") == 10
assert number_of_substrings("abcde") == 15


Input: Write a function to find the number of possible sequences of length n such that each of the next element is greater than or equal to twice of the previous element but less than or equal to m.

Answer:
def get_total_number_of_sequences(m,n):
	T=[[0 for i in range(n+1)] for i in range(m+1)]
	for i in range(m+1):
		for j in range(n+1):
			if i==0 or j==0:
				T[i][j]=0
			elif i<j:
				T[i][j]=0
			elif j==1:
				T[i][j]=i
			else:
				T[i][j]=T[i-1][j]+T[i//2][j-1]
	return T[m][n]

assert get_total_number_of_sequences(10, 4) == 4
assert get_total_number_of_sequences(5, 2) == 6
assert get_total_number_of_sequences(16, 3) == 84


Input: Write a function to replace the last element of the list with another list.

Answer:
def replace_list(list1,list2):
 list1[-1:] = list2
 replace_list=list1
 return replace_list


Input: Write a function to generate a 3d array having each element as '*'.

Answer:
def array_3d(m,n,o):
 array_3d = [[ ['*' for col in range(m)] for col in range(n)] for row in range(o)]
 return array_3d


Input: Write a function to count total characters in a string.

Answer:
def count_charac(str1):
 total = 0
 for i in str1:
    total = total + 1
 return total

assert count_charac("python programming")==18
assert count_charac("language")==8
assert count_charac("words")==5


Input: Write a function to sort the given list based on the occurrence of first element of tuples.

Answer:
def sort_on_occurence(lst):
	dct = {}
	for i, j in lst:
		dct.setdefault(i, []).append(j)
	return ([(i, *dict.fromkeys(j), len(j))
				for i, j in dct.items()])


Input: Write a python function to find the next perfect square greater than a given number.

Answer:
import math
def next_Perfect_Square(N):
    nextN = math.floor(math.sqrt(N)) + 1
    return nextN * nextN

assert next_Perfect_Square(35) == 36
assert next_Perfect_Square(6) == 9
assert next_Perfect_Square(9) == 16


Input: Write a function to find the maximum sum of bi-tonic sub-sequence for the given array.

Answer:
def max_sum(arr, n):
	MSIBS = arr[:]
	for i in range(n):
		for j in range(0, i):
			if arr[i] > arr[j] and MSIBS[i] < MSIBS[j] + arr[i]:
				MSIBS[i] = MSIBS[j] + arr[i]
	MSDBS = arr[:]
	for i in range(1, n + 1):
		for j in range(1, i):
			if arr[-i] > arr[-j] and MSDBS[-i] < MSDBS[-j] + arr[-i]:
				MSDBS[-i] = MSDBS[-j] + arr[-i]
	max_sum = float("-Inf")
	for i, j, k in zip(MSIBS, MSDBS, arr):
		max_sum = max(max_sum, i + j - k)
	return max_sum


Input: Write a function for computing square roots using the babylonian method.

Answer:
def babylonian_squareroot(number):
    if(number == 0):
        return 0;
    g = number/2.0;
    g2 = g + 1;
    while(g != g2):
        n = number/ g;
        g2 = g;
        g = (g + n)/2;
    return g;

assert babylonian_squareroot(10)==3.162277660168379
assert babylonian_squareroot(2)==1.414213562373095
assert babylonian_squareroot(9)==3.0


Input: Write a function to find the longest palindromic subsequence in the given string.

Answer:
def lps(str):
	n = len(str)
	L = [[0 for x in range(n)] for x in range(n)]
	for i in range(n):
		L[i][i] = 1
	for cl in range(2, n+1):
		for i in range(n-cl+1):
			j = i+cl-1
			if str[i] == str[j] and cl == 2:
				L[i][j] = 2
			elif str[i] == str[j]:
				L[i][j] = L[i+1][j-1] + 2
			else:
				L[i][j] = max(L[i][j-1], L[i+1][j]);
	return L[0][n-1]

assert lps("TENS FOR TENS") == 5
assert lps("CARDIO FOR CARDS") == 7
assert lps("PART OF THE JOURNEY IS PART") == 9


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

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


Input: Write a function to find the intersection of two arrays using lambda function.

Answer:
def intersection_array(array_nums1,array_nums2):
 result = list(filter(lambda x: x in array_nums1, array_nums2))
 return result


Input: Write a python function to count the occcurences of an element in a tuple.

Answer:
def count_X(tup, x):
    count = 0
    for ele in tup:
        if (ele == x):
            count = count + 1
    return count


Input: Write a function to insert an element before each element of a list.

Answer:
def insert_element(list,element):
 list = [v for elt in list for v in (element, elt)]
 return list

assert insert_element(['Red', 'Green', 'Black'] ,'c')==['c', 'Red', 'c', 'Green', 'c', 'Black']
assert insert_element(['python', 'java'] ,'program')==['program', 'python', 'program', 'java']
assert insert_element(['happy', 'sad'] ,'laugh')==['laugh', 'happy', 'laugh', 'sad']


Input: Write a python function to convert complex numbers to polar coordinates.

Answer:
import cmath
def convert(numbers):
  num = cmath.polar(numbers)
  return (num)


Input: Write a python function to count integers from a given list.

Answer:
def count_integer(list1):
    ctr = 0
    for i in list1:
        if isinstance(i, int):
            ctr = ctr + 1
    return ctr

assert count_integer([1,2,'abc',1.2]) == 2
assert count_integer([1,2,3]) == 3
assert count_integer([1,1.2,4,5.1]) == 2


Input: Write a function to find all words starting with 'a' or 'e' in a given string.

Answer:
import re
def words_ae(text):
 list = re.findall("[ae]\w+", text)
 return list

assert words_ae("python programe")==['ame']
assert words_ae("python programe language")==['ame','anguage']
assert words_ae("assert statement")==['assert', 'atement']


Input: Write a function to choose specified number of colours from three different colours and generate all the combinations with repetitions.

Answer:
from itertools import combinations_with_replacement
def combinations_colors(l, n):
    return list(combinations_with_replacement(l,n))

assert combinations_colors( ["Red","Green","Blue"],1)==[('Red',), ('Green',), ('Blue',)]
assert combinations_colors( ["Red","Green","Blue"],2)==[('Red', 'Red'), ('Red', 'Green'), ('Red', 'Blue'), ('Green', 'Green'), ('Green', 'Blue'), ('Blue', 'Blue')]
assert combinations_colors( ["Red","Green","Blue"],3)==[('Red', 'Red', 'Red'), ('Red', 'Red', 'Green'), ('Red', 'Red', 'Blue'), ('Red', 'Green', 'Green'), ('Red', 'Green', 'Blue'), ('Red', 'Blue', 'Blue'), ('Green', 'Green', 'Green'), ('Green', 'Green', 'Blue'), ('Green', 'Blue', 'Blue'), ('Blue', 'Blue', 'Blue')]


Input: Write a python function to count the number of prime numbers less than a given non-negative number.

Answer:
def count_Primes_nums(n):
    ctr = 0
    for num in range(n):
        if num <= 1:
            continue
        for i in range(2,num):
            if (num % i) == 0:
                break
        else:
            ctr += 1
    return ctr

assert count_Primes_nums(5) == 2
assert count_Primes_nums(10) == 4
assert count_Primes_nums(100) == 25


Input: Write a function to swap two numbers.

Answer:
def swap_numbers(a,b):
 temp = a
 a = b
 b = temp
 return (a,b)


Input: Write a function to find number of odd elements in the given list using lambda function.

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


Input: Write a function to maximize the given two tuples.

Answer:
def maximize_elements(test_tup1, test_tup2):
  res = tuple(tuple(max(a, b) for a, b in zip(tup1, tup2))
   for tup1, tup2 in zip(test_tup1, test_tup2))
  return (res)


Input: Write a function to find the nth newman–shanks–williams prime number.

Answer:
def newman_prime(n):
	if n == 0 or n == 1:
		return 1
	return 2 * newman_prime(n - 1) + newman_prime(n - 2)

assert newman_prime(3) == 7
assert newman_prime(4) == 17
assert newman_prime(5) == 41


Input: Write a function to perform mathematical division operation across the given tuples.

Answer:
def division_elements(test_tup1, test_tup2):
  res = tuple(ele1 // ele2 for ele1, ele2 in zip(test_tup1, test_tup2))
  return (res)


Input: Write a function to split a given list into two parts where the length of the first part of the list is given.

Answer:
def split_two_parts(list1, L):
    return list1[:L], list1[L:]


Input: Write a function to merge two dictionaries.

Answer:
def merge_dict(d1,d2):
 d = d1.copy()
 d.update(d2)
 return d


Input: Write a function to calculate a dog's age in dog's years.

Answer:
def dog_age(h_age):
 if h_age < 0:
 	exit()
 elif h_age <= 2:
	 d_age = h_age * 10.5
 else:
	 d_age = 21 + (h_age - 2)*4
 return d_age

assert dog_age(12)==61
assert dog_age(15)==73
assert dog_age(24)==109


Input: Write a function to split a list for every nth element.

Answer:
def list_split(S, step):
    return [S[i::step] for i in range(step)]


Input: Write a function to find the lateral surface area of a cube.

Answer:
def lateralsurface_cube(l):
  LSA = 4 * (l * l)
  return LSA

assert lateralsurface_cube(5)==100
assert lateralsurface_cube(9)==324
assert lateralsurface_cube(10)==400


Input: Write a python function to find the sum of squares of first n odd natural numbers.

Answer:
def square_Sum(n):
    return int(n*(4*n*n-1)/3)

assert square_Sum(2) == 10
assert square_Sum(3) == 35
assert square_Sum(4) == 84


Input: Write a function to find the n'th star number.

Answer:
def find_star_num(n):
	return (6 * n * (n - 1) + 1)

assert find_star_num(3) == 37
assert find_star_num(4) == 73
assert find_star_num(5) == 121


Input: Write a function to find the ascii value of a character.

Answer:
def ascii_value(k):
  ch=k
  return ord(ch)

assert ascii_value('A')==65
assert ascii_value('R')==82
assert ascii_value('S')==83


Input: Write a python function to find the sum of even numbers at even positions.

Answer:
def sum_even_and_even_index(arr,n):
    i = 0
    sum = 0
    for i in range(0,n,2):
        if (arr[i] % 2 == 0) :
            sum += arr[i]
    return sum


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

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

assert even_Power_Sum(2) == 1056
assert even_Power_Sum(3) == 8832
assert even_Power_Sum(1) == 32


Input: Write a function to perfom the rear element extraction from list of tuples records.

Answer:
def rear_extract(test_list):
  res = [lis[-1] for lis in test_list]
  return (res)


Input: Write a function to substract the contents of one tuple with corresponding index of other tuple.

Answer:
def substract_elements(test_tup1, test_tup2):
  res = tuple(map(lambda i, j: i - j, test_tup1, test_tup2))
  return (res)


Input: Write a python function to find sum of even index binomial coefficients.

Answer:
import math
def even_binomial_Coeff_Sum( n):
    return (1 << (n - 1))

assert even_binomial_Coeff_Sum(4) == 8
assert even_binomial_Coeff_Sum(6) == 32
assert even_binomial_Coeff_Sum(2) == 2


Input: Write a python function to find the position of the last removed element from the given array.

Answer:
import math as mt
def get_Position(a,n,m):
    for i in range(n):
        a[i] = (a[i] // m + (a[i] % m != 0))
    result,maxx = -1,-1
    for i in range(n - 1,-1,-1):
        if (maxx < a[i]):
            maxx = a[i]
            result = i
    return result + 1

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


Input: Write a function to find the volume of a cylinder.

Answer:
def volume_cylinder(r,h):
  volume=3.1415*r*r*h
  return volume


Input: Write a function to filter a dictionary based on values.

Answer:
def dict_filter(dict,n):
 result = {key:value for (key, value) in dict.items() if value >=n}
 return result

assert dict_filter({'Cierra Vega': 175, 'Alden Cantrell': 180, 'Kierra Gentry': 165, 'Pierre Cox': 190},170)=={'Cierra Vega': 175, 'Alden Cantrell': 180, 'Pierre Cox': 190}
assert dict_filter({'Cierra Vega': 175, 'Alden Cantrell': 180, 'Kierra Gentry': 165, 'Pierre Cox': 190},180)=={ 'Alden Cantrell': 180, 'Pierre Cox': 190}
assert dict_filter({'Cierra Vega': 175, 'Alden Cantrell': 180, 'Kierra Gentry': 165, 'Pierre Cox': 190},190)=={ 'Pierre Cox': 190}


Input: Write a function to find the element count that occurs before the record in the given tuple.

Answer:
def count_first_elements(test_tup):
  for count, ele in enumerate(test_tup):
    if isinstance(ele, tuple):
      break
  return (count)

assert count_first_elements((1, 5, 7, (4, 6), 10) ) == 3
assert count_first_elements((2, 9, (5, 7), 11) ) == 2
assert count_first_elements((11, 15, 5, 8, (2, 3), 8) ) == 4


Input: Write a function to find the nth decagonal number.

Answer:
def is_num_decagonal(n):
	return 4 * n * n - 3 * n

assert is_num_decagonal(3) == 27
assert is_num_decagonal(7) == 175
assert is_num_decagonal(10) == 370


Input: Write a function to search an element in the given array by using sequential search.

Answer:
def sequential_search(dlist, item):
    pos = 0
    found = False
    while pos < len(dlist) and not found:
        if dlist[pos] == item:
            found = True
        else:
            pos = pos + 1
    return found, pos


Input: Write a python function to check if the elements of a given list are unique or not.

Answer:
def all_unique(test_list):
    if len(test_list) > len(set(test_list)):
        return False
    return True

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


Input: Write a function to substaract two lists using map and lambda function.

Answer:
def sub_list(nums1,nums2):
  result = map(lambda x, y: x - y, nums1, nums2)
  return list(result)


Input: Write a python function to check whether the frequency of each digit is less than or equal to the digit itself.

Answer:
def validate(n):
    for i in range(10):
        temp = n;
        count = 0;
        while (temp):
            if (temp % 10 == i):
                count+=1;
            if (count > i):
                return False
            temp //= 10;
    return True

assert validate(1234) == True
assert validate(51241) == False
assert validate(321) == True


Input: Write a function to check whether all items of a list are equal to a given string.

Answer:
def check_element(list,element):
  check_element=all(v== element for v in list)
  return check_element

assert check_element(["green", "orange", "black", "white"],'blue')==False
assert check_element([1,2,3,4],7)==False
assert check_element(["green", "green", "green", "green"],'green')==True


Input: Write a function that matches a string that has an a followed by two to three 'b'.

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

assert text_match_two_three("ac")==('Not matched!')
assert text_match_two_three("dc")==('Not matched!')
assert text_match_two_three("abbbba")==('Found a match!')


Input: Write a function to find the largest sum of contiguous array in the modified array which is formed by repeating the given array k times.

Answer:
def max_sub_array_sum_repeated(a, n, k):
	max_so_far = -2147483648
	max_ending_here = 0
	for i in range(n*k):
		max_ending_here = max_ending_here + a[i%n]
		if (max_so_far < max_ending_here):
			max_so_far = max_ending_here
		if (max_ending_here < 0):
			max_ending_here = 0
	return max_so_far

assert max_sub_array_sum_repeated([10, 20, -30, -1], 4, 3) == 30
assert max_sub_array_sum_repeated([-1, 10, 20], 3, 2) == 59
assert max_sub_array_sum_repeated([-1, -2, -3], 3, 3) == -1


Input: Write a python function to find the sum of squares of first n even natural numbers.

Answer:
def square_Sum(n):
    return int(2*n*(n+1)*(2*n+1)/3)

assert square_Sum(2) == 20
assert square_Sum(3) == 56
assert square_Sum(4) == 120


Input: Write a function to count array elements having modular inverse under given prime number p equal to itself.

Answer:
def modular_inverse(arr, N, P):
	current_element = 0
	for i in range(0, N):
		if ((arr[i] * arr[i]) % P == 1):
			current_element = current_element + 1
	return current_element


Input: Write a python function to calculate the number of odd days in a given year.

Answer:
def odd_Days(N):
    hund1 = N // 100
    hund4 = N // 400
    leap = N >> 2
    ordd = N - leap
    if (hund1):
        ordd += hund1
        leap -= hund1
    if (hund4):
        ordd -= hund4
        leap += hund4
    days = ordd + leap * 2
    odd = days % 7
    return odd

assert odd_Days(100) == 5
assert odd_Days(50) ==6
assert odd_Days(75) == 2


Input: Write a function to find the list of lists with maximum length.

Answer:
def max_length(list1):
    max_length = max(len(x) for x in  list1 )
    max_list = max((x) for x in   list1)
    return(max_length, max_list)


Input: Write a function to find out the number of ways of painting the fence such that at most 2 adjacent posts have the same color for the given fence with n posts and k colors.

Answer:
def count_no_of_ways(n, k):
	dp = [0] * (n + 1)
	total = k
	mod = 1000000007
	dp[1] = k
	dp[2] = k * k
	for i in range(3,n+1):
		dp[i] = ((k - 1) * (dp[i - 1] + dp[i - 2])) % mod
	return dp[n]

assert count_no_of_ways(2, 4) == 16
assert count_no_of_ways(3, 2) == 6
assert count_no_of_ways(4, 4) == 228


Input: Write a python function to find quotient of two numbers.

Answer:
def find(n,m):
    q = n//m
    return (q)

assert find(10,3) == 3
assert find(4,2) == 2
assert find(20,5) == 4


Input: Write a function to find the third side of a right angled triangle.

Answer:
import math
def otherside_rightangle(w,h):
  s=math.sqrt((w*w)+(h*h))
  return s

assert otherside_rightangle(7,8)==10.63014581273465
assert otherside_rightangle(3,4)==5
assert otherside_rightangle(7,15)==16.55294535724685


Input: Write a function to find the maximum value in a given heterogeneous list.

Answer:
def max_val(listval):
     max_val = max(i for i in listval if isinstance(i, int))
     return(max_val)

assert max_val(['Python', 3, 2, 4, 5, 'version'])==5
assert max_val(['Python', 15, 20, 25])==25
assert max_val(['Python', 30, 20, 40, 50, 'version'])==50


Input: Write a function to return the sum of all divisors of a number.

Answer:
def sum_div(number):
    divisors = [1]
    for i in range(2, number):
        if (number % i)==0:
            divisors.append(i)
    return sum(divisors)

assert sum_div(8)==7
assert sum_div(12)==16
assert sum_div(7)==1


Input: Write a python function to count inversions in an array.

Answer:
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


Input: Write a function to flatten a given nested list structure.

Answer:
def flatten_list(list1):
    result_list = []
    if not list1: return result_list
    stack = [list(list1)]
    while stack:
        c_num = stack.pop()
        next = c_num.pop()
        if c_num: stack.append(c_num)
        if isinstance(next, list):
            if next: stack.append(list(next))
        else: result_list.append(next)
    result_list.reverse()
    return result_list


Input: Write a function to find the nested list elements which are present in another list.

Answer:
def intersection_nested_lists(l1, l2):
    result = [[n for n in lst if n in l1] for lst in l2]
    return result


Input: Write a function to calculate the maximum aggregate from the list of tuples.

Answer:
from collections import defaultdict
def max_aggregate(stdata):
    temp = defaultdict(int)
    for name, marks in stdata:
        temp[name] += marks
    return max(temp.items(), key=lambda x: x[1])

assert max_aggregate([('Juan Whelan',90),('Sabah Colley',88),('Peter Nichols',7),('Juan Whelan',122),('Sabah Colley',84)])==('Juan Whelan', 212)
assert max_aggregate([('Juan Whelan',50),('Sabah Colley',48),('Peter Nichols',37),('Juan Whelan',22),('Sabah Colley',14)])==('Juan Whelan', 72)
assert max_aggregate([('Juan Whelan',10),('Sabah Colley',20),('Peter Nichols',30),('Juan Whelan',40),('Sabah Colley',50)])==('Sabah Colley', 70)


Input: Write a function to find the count of all binary sequences of length 2n such that sum of first n bits is same as sum of last n bits.

Answer:
def count_binary_seq(n):
	nCr = 1
	res = 1
	for r in range(1, n + 1):
		nCr = (nCr * (n + 1 - r)) / r
		res += nCr * nCr
	return res

assert count_binary_seq(1) == 2.0
assert count_binary_seq(2) == 6.0
assert count_binary_seq(3) == 20.0


Input: Write a function to find the depth of a dictionary.

Answer:
def dict_depth(d):
    if isinstance(d, dict):
        return 1 + (max(map(dict_depth, d.values())) if d else 0)
    return 0


Input: Write a python function to find the most significant bit number which is also a set bit.

Answer:
def set_Bit_Number(n):
    if (n == 0):
        return 0;
    msb = 0;
    n = int(n / 2);
    while (n > 0):
        n = int(n / 2);
        msb += 1;
    return (1 << msb)

assert set_Bit_Number(6) == 4
assert set_Bit_Number(10) == 8
assert set_Bit_Number(18) == 16


Input: Write a python function to check whether the count of inversion of two types are same or not.

Answer:
import sys
def solve(a,n):
    mx = -sys.maxsize - 1
    for j in range(1,n):
        if (mx > a[j]):
            return False
        mx = max(mx,a[j - 1])
    return True

assert solve([1,0,2],3) == True
assert solve([1,2,0],3) == False
assert solve([1,2,1],3) == True


Input: Write a python function to find element at a given index after number of rotations.

Answer:
def find_Element(arr,ranges,rotations,index) :
    for i in range(rotations - 1,-1,-1 ) :
        left = ranges[i][0]
        right = ranges[i][1]
        if (left <= index and right >= index) :
            if (index == left) :
                index = right
            else :
                index = index - 1
    return arr[index]


Input: Write a function to match two words from a list of words starting with letter 'p'.

Answer:
import re
def start_withp(words):
 for w in words:
        m = re.match("(P\w+)\W(P\w+)", w)
        if m:
            return m.groups()

assert start_withp(["Python PHP", "Java JavaScript", "c c++"])==('Python', 'PHP')
assert start_withp(["Python Programming","Java Programming"])==('Python','Programming')
assert start_withp(["Pqrst Pqr","qrstuv"])==('Pqrst','Pqr')


Input: Write a function to find the maximum sum of increasing subsequence from prefix till ith index and also including a given kth element which is after i, i.e., k > i .

Answer:
def max_sum_increasing_subseq(a, n, index, k):
	dp = [[0 for i in range(n)]
			for i in range(n)]
	for i in range(n):
		if a[i] > a[0]:
			dp[0][i] = a[i] + a[0]
		else:
			dp[0][i] = a[i]
	for i in range(1, n):
		for j in range(n):
			if a[j] > a[i] and j > i:
				if dp[i - 1][i] + a[j] > dp[i - 1][j]:
					dp[i][j] = dp[i - 1][i] + a[j]
				else:
					dp[i][j] = dp[i - 1][j]
			else:
				dp[i][j] = dp[i - 1][j]
	return dp[index][k]


Input: Write a function to get a colon of a tuple.

Answer:
from copy import deepcopy
def colon_tuplex(tuplex,m,n):
  tuplex_colon = deepcopy(tuplex)
  tuplex_colon[m].append(n)
  return tuplex_colon

assert colon_tuplex(("HELLO", 5, [], True) ,2,50)==("HELLO", 5, [50], True)
assert colon_tuplex(("HELLO", 5, [], True) ,2,100)==(("HELLO", 5, [100],True))
assert colon_tuplex(("HELLO", 5, [], True) ,2,500)==("HELLO", 5, [500], True)


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

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


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

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

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


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

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


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

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

assert set_left_most_unset_bit(10) == 14
assert set_left_most_unset_bit(12) == 14
assert set_left_most_unset_bit(15) == 15


Input: Write a function to find the volume of a cone.

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


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

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


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

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


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

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

assert find_Max_Len_Even("python language") == "language"
assert find_Max_Len_Even("maximum even length") == "length"
assert find_Max_Len_Even("eve") == "-1"


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

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


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

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


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

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

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


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

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

assert find_long_word('Please move back to strem') == ['strem']
assert find_long_word('4K Ultra HD streaming player') == ['Ultra']
assert find_long_word('Streaming Media Player') == ['Media']


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

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

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


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

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


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

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


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

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


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

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


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

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

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


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

Answer:
from collections import defaultdict

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

assert most_occurrences(["UTS is best for RTF", "RTF love UTS", "UTS is best"] ) == 'UTS'
assert most_occurrences(["Its been a great year", "this year is so worse", "this year is okay"] ) == 'year'
assert most_occurrences(["Families can be reunited", "people can be reunited", "Tasks can be achieved "] ) == 'can'


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

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

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


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

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


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

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


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

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

assert find_char('For the four consumer complaints contact manager AKR reddy') == ['For', 'the', 'four', 'AKR', 'reddy']
assert find_char('Certain service are subject to change MSR') == ['are', 'MSR']
assert find_char('Third party legal desclaimers') == ['Third', 'party', 'legal']


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

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

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


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

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


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

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


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

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

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


Input: Write a function to find the sum of arithmetic progression.

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


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

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

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


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

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

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


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

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

assert count_Substring_With_Equal_Ends('aba') == 4
assert count_Substring_With_Equal_Ends('abcab') == 7
assert count_Substring_With_Equal_Ends('abc') == 3


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

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

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


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

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

assert sum_three_smallest_nums([10,20,30,40,50,60,7]) == 37
assert sum_three_smallest_nums([1,2,3,4,5]) == 6
assert sum_three_smallest_nums([0,1,2,3,4,5]) == 6


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

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


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

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


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

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

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


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

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

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


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

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


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

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

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


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

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

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


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

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

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


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

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

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


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

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

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


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

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


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

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

assert unique_Characters('aba') == False
assert unique_Characters('abc') == True
assert unique_Characters('abab') == False


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

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


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

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