question
stringlengths
37
191
answer
stringlengths
37
1.33k
Write a function to convert the given snake case string to camel case string by using regex.
import re def snake_to_camel(word): return ''.join(x.capitalize() or '_' for x in word.split('_'))
Write a python function to remove odd numbers from a given list.
def remove_odd(l): for i in l: if i % 2 != 0: l.remove(i) return l
Write a function to extract the nth element from a given list of tuples.
def extract_nth_element(list1, n): result = [x[n] for x in list1] return result
Write a python function to check whether the value exists in a sequence or not.
def overlapping(list1,list2): c=0 d=0 for i in list1: c+=1 for i in list2: d+=1 for i in range(0,c): for j in range(0,d): if(list1[i]==list2[j]): return 1 return 0
Write a python function to find a pair with highest product from a given array of integers.
def max_Product(arr): arr_len = len(arr) if (arr_len < 2): return ("No pairs exists") x = arr[0]; y = arr[1] for i in range(0,arr_len): for j in range(i + 1,arr_len): if (arr[i] * arr[j] > x * y): x = arr[i]; y = arr[j] return x,y
Write a function to find the maximum sum we can make by dividing number in three parts recursively and summing them up together for the given number.
MAX = 1000000 def breakSum(n): dp = [0]*(n+1) dp[0] = 0 dp[1] = 1 for i in range(2, n+1): dp[i] = max(dp[int(i/2)] + dp[int(i/3)] + dp[int(i/4)], i); return dp[n]
Write a function to find common first element in given list of tuple.
def group_tuples(Input): out = {} for elem in Input: try: out[elem[0]].extend(elem[1:]) except KeyError: out[elem[0]] = list(elem) return [tuple(values) for values in out.values()]
Write a python function to find the sublist having maximum length.
def Find_Max(lst): maxList = max((x) for x in lst) return maxList
Write a function to round every number of a given list of numbers and print the total sum multiplied by the length of the list.
def round_and_sum(list1): lenght=len(list1) round_and_sum=sum(list(map(round,list1))* lenght) return round_and_sum
Write a python function to find the cube sum of first n even natural numbers.
def cube_Sum(n): sum = 0 for i in range(1,n + 1): sum += (2*i)*(2*i)*(2*i) return sum
Write a function to concatenate each element of tuple by the delimiter.
def concatenate_tuple(test_tup): delim = "-" res = ''.join([str(ele) + delim for ele in test_tup]) res = res[ : len(res) - len(delim)] return (str(res))
Write a python function to find the average of cubes of first n natural numbers.
def find_Average_Of_Cube(n): sum = 0 for i in range(1, n + 1): sum += i * i * i return round(sum / n, 6)
Write a function to solve gold mine problem.
def get_maxgold(gold, m, n): goldTable = [[0 for i in range(n)] for j in range(m)] for col in range(n-1, -1, -1): for row in range(m): if (col == n-1): right = 0 else: right = goldTable[row][col+1] if (row == 0 or col == n-1): right_up = 0 else: right_up = goldTable[row-1][col+1] if (row == m-1 or col == n-1): right_down = 0 else: right_down = goldTable[row+1][col+1] goldTable[row][col] = gold[row][col] + max(right, right_up, right_down) res = goldTable[0][0] for i in range(1, m): res = max(res, goldTable[i][0]) return res
Write a function to extract only the rear index element of each string in the given tuple.
def extract_rear(test_tuple): res = list(sub[len(sub) - 1] for sub in test_tuple) return (res)
Write a function to count the number of sublists containing a particular element.
def count_element_in_list(list1, x): ctr = 0 for i in range(len(list1)): if x in list1[i]: ctr+= 1 return ctr
Write a function to filter odd numbers using lambda function.
def filter_oddnumbers(nums): odd_nums = list(filter(lambda x: x%2 != 0, nums)) return odd_nums
Write a function to convert a date of yyyy-mm-dd format to dd-mm-yyyy format by using regex.
import re def change_date_format(dt): return re.sub(r'(\d{4})-(\d{1,2})-(\d{1,2})', '\\3-\\2-\\1', dt)
Write a function to sort the given array by using shell sort.
def shell_sort(my_list): gap = len(my_list) // 2 while gap > 0: for i in range(gap, len(my_list)): current_item = my_list[i] j = i while j >= gap and my_list[j - gap] > current_item: my_list[j] = my_list[j - gap] j -= gap my_list[j] = current_item gap //= 2 return my_list
Write a function to extract the elementwise and tuples from the given two tuples.
def and_tuples(test_tup1, test_tup2): res = tuple(ele1 & ele2 for ele1, ele2 in zip(test_tup1, test_tup2)) return (res)
Write a function to find the directrix of a parabola.
def parabola_directrix(a, b, c): directrix=((int)(c - ((b * b) + 1) * 4 * a )) return directrix
Write a function that takes two lists and returns true if they have at least one common element.
def common_element(list1, list2): result = False for x in list1: for y in list2: if x == y: result = True return result
Write a function to find the median of a trapezium.
def median_trapezium(base1,base2,height): median = 0.5 * (base1+ base2) return median
Write a function to check whether the entered number is greater than the elements of the given array.
def check_greater(arr, number): arr.sort() if number > arr[-1]: return ('Yes, the entered number is greater than those in the array') else: return ('No, entered number is less than those in the array')
Write a function that matches a string that has an a followed by one or more b's.
import re def text_match_one(text): patterns = 'ab+?' if re.search(patterns, text): return 'Found a match!' else: return('Not matched!')
Write a python function to find the last digit of a given number.
def last_Digit(n) : return (n % 10)
Write a python function to print negative numbers in a list.
def neg_nos(list1): for num in list1: if num < 0: return num
Write a function to remove odd characters in a string.
def remove_odd(str1): str2 = '' for i in range(1, len(str1) + 1): if(i % 2 == 0): str2 = str2 + str1[i - 1] return str2
Write a function to count bidirectional tuple pairs.
def count_bidirectional(test_list): res = 0 for idx in range(0, len(test_list)): for iidx in range(idx + 1, len(test_list)): if test_list[iidx][0] == test_list[idx][1] and test_list[idx][1] == test_list[iidx][0]: res += 1 return (str(res))
Write a function to convert a list of multiple integers into a single integer.
def multiple_to_single(L): x = int("".join(map(str, L))) return x
Write a function to find all adverbs and their positions in a given sentence.
import re def find_adverb_position(text): for m in re.finditer(r"\w+ly", text): return (m.start(), m.end(), m.group(0))
Write a function to find the surface area of a cube.
def surfacearea_cube(l): surfacearea= 6*l*l return surfacearea
Write a function to find the ration of positive numbers in an array of integers.
from array import array def positive_count(nums): n = len(nums) n1 = 0 for x in nums: if x > 0: n1 += 1 else: None return round(n1/n,2)
Write a python function to find the largest negative number from the given list.
def largest_neg(list1): max = list1[0] for x in list1: if x < max : max = x return max
Write a function to trim each tuple by k in the given tuple list.
def trim_tuple(test_list, K): res = [] for ele in test_list: N = len(ele) res.append(tuple(list(ele)[K: N - K])) return (str(res))
Write a function to perform index wise multiplication of tuple elements in the given two tuples.
def index_multiplication(test_tup1, test_tup2): res = tuple(tuple(a * b for a, b in zip(tup1, tup2)) for tup1, tup2 in zip(test_tup1, test_tup2)) return (res)
Write a python function to count the occurence of all elements of list in a tuple.
from collections import Counter def count_Occurrence(tup, lst): count = 0 for item in tup: if item in lst: count+= 1 return count
Write a function to find cubes of individual elements in a list using lambda function.
def cube_nums(nums): cube_nums = list(map(lambda x: x ** 3, nums)) return cube_nums
Write a function to calculate the sum of perrin numbers.
def cal_sum(n): a = 3 b = 0 c = 2 if (n == 0): return 3 if (n == 1): return 3 if (n == 2): return 5 sum = 5 while (n > 2): d = a + b sum = sum + d a = b b = c c = d n = n-1 return sum
Write a python function to check whether the triangle is valid or not if 3 points are given.
def check_Triangle(x1,y1,x2,y2,x3,y3): a = (x1*(y2-y3)+x2*(y3-y1)+x3*(y1-y2)) if a == 0: return ('No') else: return ('Yes')
Write a function to extract specified size of strings from a give list of string values.
def extract_string(str, l): result = [e for e in str if len(e) == l] return result
Write a function to remove all whitespaces from the given string using regex.
import re def remove_whitespaces(text1): return (re.sub(r'\s+', '',text1))
Write a function that gives loss amount if the given amount has loss else return none.
def loss_amount(actual_cost,sale_amount): if(sale_amount > actual_cost): amount = sale_amount - actual_cost return amount else: return None
Write a python function to find the sum of even factors of a number.
import math def sumofFactors(n) : if (n % 2 != 0) : return 0 res = 1 for i in range(2, (int)(math.sqrt(n)) + 1) : count = 0 curr_sum = 1 curr_term = 1 while (n % i == 0) : count= count + 1 n = n // i if (i == 2 and count == 1) : curr_sum = 0 curr_term = curr_term * i curr_sum = curr_sum + curr_term res = res * curr_sum if (n >= 2) : res = res * (1 + n) return res
Write a function that matches a word containing 'z'.
import re def text_match_wordz(text): patterns = '\w*z.\w*' if re.search(patterns, text): return 'Found a match!' else: return('Not matched!')
Write a function to check whether the given month number contains 31 days or not.
def check_monthnumb_number(monthnum2): if(monthnum2==1 or monthnum2==3 or monthnum2==5 or monthnum2==7 or monthnum2==8 or monthnum2==10 or monthnum2==12): return True else: return False
Write a function to reverse strings in a given list of string values.
def reverse_string_list(stringlist): result = [x[::-1] for x in stringlist] return result
Write a python function to find the sublist having minimum length.
def Find_Min(lst): minList = min((x) for x in lst) return minList
Write a function to find the area of a rectangle.
def rectangle_area(l,b): area=l*b return area
Write a function to remove uppercase substrings from a given string by using regex.
import re def remove_uppercase(str1): remove_upper = lambda text: re.sub('[A-Z]', '', text) result = remove_upper(str1) return (result)
Write a python function to get the first element of each sublist.
def Extract(lst): return [item[0] for item in lst]
Write a python function to count the upper case characters in a given string.
def upper_ctr(str): upper_ctr = 0 for i in range(len(str)): if str[i] >= 'A' and str[i] <= 'Z': upper_ctr += 1 return upper_ctr
Write a function to find all possible combinations of the elements of a given list.
def combinations_list(list1): if len(list1) == 0: return [[]] result = [] for el in combinations_list(list1[1:]): result += [el, el+[list1[0]]] return result
Write a function to find the maximum product subarray of the given array.
def max_subarray_product(arr): n = len(arr) max_ending_here = 1 min_ending_here = 1 max_so_far = 0 flag = 0 for i in range(0, n): if arr[i] > 0: max_ending_here = max_ending_here * arr[i] min_ending_here = min (min_ending_here * arr[i], 1) flag = 1 elif arr[i] == 0: max_ending_here = 1 min_ending_here = 1 else: temp = max_ending_here max_ending_here = max (min_ending_here * arr[i], 1) min_ending_here = temp * arr[i] if (max_so_far < max_ending_here): max_so_far = max_ending_here if flag == 0 and max_so_far == 0: return 0 return max_so_far
Write a function to check if all values are same in a dictionary.
def check_value(dict, n): result = all(x == n for x in dict.values()) return result
Write a function to drop empty items from a given dictionary.
def drop_empty(dict1): dict1 = {key:value for (key, value) in dict1.items() if value is not None} return dict1
Write a function to find the peak element in the given array.
def find_peak_util(arr, low, high, n): mid = low + (high - low)/2 mid = int(mid) if ((mid == 0 or arr[mid - 1] <= arr[mid]) and (mid == n - 1 or arr[mid + 1] <= arr[mid])): return mid elif (mid > 0 and arr[mid - 1] > arr[mid]): return find_peak_util(arr, low, (mid - 1), n) else: return find_peak_util(arr, (mid + 1), high, n) def find_peak(arr, n): return find_peak_util(arr, 0, n - 1, n)
Write a python function to convert decimal number to octal number.
def decimal_to_Octal(deciNum): octalNum = 0 countval = 1; dNo = deciNum; while (deciNum!= 0): remainder= deciNum % 8; octalNum+= remainder*countval; countval= countval*10; deciNum //= 8; return (octalNum)
Write a function to find the maximum product formed by multiplying numbers of an increasing subsequence of that array.
def max_product(arr, n ): mpis =[0] * (n) for i in range(n): mpis[i] = arr[i] for i in range(1, n): for j in range(i): if (arr[i] > arr[j] and mpis[i] < (mpis[j] * arr[i])): mpis[i] = mpis[j] * arr[i] return max(mpis)
Write a function to find the maximum profit earned from a maximum of k stock transactions
def max_profit(price, k): n = len(price) final_profit = [[None for x in range(n)] for y in range(k + 1)] for i in range(k + 1): for j in range(n): if i == 0 or j == 0: final_profit[i][j] = 0 else: max_so_far = 0 for x in range(j): curr_price = price[j] - price[x] + final_profit[i-1][x] if max_so_far < curr_price: max_so_far = curr_price final_profit[i][j] = max(final_profit[i][j-1], max_so_far) return final_profit[k][n-1]
Write a function to find the pairwise addition of the elements of the given tuples.
def add_pairwise(test_tup): res = tuple(i + j for i, j in zip(test_tup, test_tup[1:])) return (res)
Write a python function to find remainder of array multiplication divided by n.
def find_remainder(arr, lens, n): mul = 1 for i in range(lens): mul = (mul * (arr[i] % n)) % n return mul % n
Write a python function to check whether the given list contains consecutive numbers or not.
def check_Consecutive(l): return sorted(l) == list(range(min(l),max(l)+1))
Write a function to find the tuple intersection of elements in the given tuple list irrespective of their order.
def tuple_intersection(test_list1, test_list2): res = set([tuple(sorted(ele)) for ele in test_list1]) & set([tuple(sorted(ele)) for ele in test_list2]) return (res)
Write a function to replace characters in a string.
def replace_char(str1,ch,newch): str2 = str1.replace(ch, newch) return str2
Write a function to sort counter by value.
from collections import Counter def sort_counter(dict1): x = Counter(dict1) sort_counter=x.most_common() return sort_counter
Write a python function to find the sum of the largest and smallest value in a given array.
def big_sum(nums): sum= max(nums)+min(nums) return sum
Write a python function to convert the given string to lower case.
def is_lower(string): return (string.lower())
Write a function to remove lowercase substrings from a given string.
import re def remove_lowercase(str1): remove_lower = lambda text: re.sub('[a-z]', '', text) result = remove_lower(str1) return result
Write a python function to find the first digit of a given number.
def first_Digit(n) : while n >= 10: n = n / 10; return int(n)
Write a python function to find the maximum occurring character in a given string.
def get_max_occuring_char(str1): ASCII_SIZE = 256 ctr = [0] * ASCII_SIZE max = -1 ch = '' for i in str1: ctr[ord(i)]+=1; for i in str1: if max < ctr[ord(i)]: max = ctr[ord(i)] ch = i return ch
Write a function to determine if there is a subset of the given set with sum equal to the given sum.
def is_subset_sum(set, n, sum): if (sum == 0): return True if (n == 0): return False if (set[n - 1] > sum): return is_subset_sum(set, n - 1, sum) return is_subset_sum(set, n-1, sum) or is_subset_sum(set, n-1, sum-set[n-1])
Write a function to find sequences of one upper case letter followed by lower case letters in the given string by using regex.
import re def match(text): pattern = '[A-Z]+[a-z]+$' if re.search(pattern, text): return('Yes') else: return('No')
Write a python function to find the first natural number whose factorial is divisible by x.
def first_Factorial_Divisible_Number(x): i = 1; fact = 1; for i in range(1,x): fact = fact * i if (fact % x == 0): break return i
Write a function to remove the matching tuples from the given two tuples.
def remove_matching_tuple(test_list1, test_list2): res = [sub for sub in test_list1 if sub not in test_list2] return (res)
Write a function to find the largest palindromic number in the given array.
def is_palindrome(n) : divisor = 1 while (n / divisor >= 10) : divisor *= 10 while (n != 0) : leading = n // divisor trailing = n % 10 if (leading != trailing) : return False n = (n % divisor) // 10 divisor = divisor // 100 return True def largest_palindrome(A, n) : A.sort() for i in range(n - 1, -1, -1) : if (is_palindrome(A[i])) : return A[i] return -1
Write a function to compute binomial probability for the given number.
def nCr(n, r): if (r > n / 2): r = n - r answer = 1 for i in range(1, r + 1): answer *= (n - r + i) answer /= i return answer def binomial_probability(n, k, p): return (nCr(n, k) * pow(p, k) * pow(1 - p, n - k))
Write a function to sort a list of tuples in increasing order by the last element in each tuple.
def sort_tuple(tup): lst = len(tup) for i in range(0, lst): for j in range(0, lst-i-1): if (tup[j][-1] > tup[j + 1][-1]): temp = tup[j] tup[j]= tup[j + 1] tup[j + 1]= temp return tup
Write a function to find the area of a pentagon.
import math def area_pentagon(a): area=(math.sqrt(5*(5+2*math.sqrt(5)))*pow(a,2))/4.0 return area
Write a python function to find the frequency of the largest value in a given array.
def frequency_Of_Largest(n,arr): mn = arr[0] freq = 1 for i in range(1,n): if (arr[i] >mn): mn = arr[i] freq = 1 elif (arr[i] == mn): freq += 1 return freq
Write a function to extract all the pairs which are symmetric in the given tuple list.
def extract_symmetric(test_list): temp = set(test_list) & {(b, a) for a, b in test_list} res = {(a, b) for a, b in temp if a < b} return (res)
Write a function to find the sum of geometric progression series.
import math def sum_gp(a,n,r): total = (a * (1 - math.pow(r, n ))) / (1- r) return total
Write a function to search an element in the given array by using binary search.
def binary_search(item_list,item): first = 0 last = len(item_list)-1 found = False while( first<=last and not found): mid = (first + last)//2 if item_list[mid] == item : found = True else: if item < item_list[mid]: last = mid - 1 else: first = mid + 1 return found
Write a function to calculate a grid of hexagon coordinates where function returns a list of lists containing 6 tuples of x, y point coordinates.
import math def calculate_polygons(startx, starty, endx, endy, radius): sl = (2 * radius) * math.tan(math.pi / 6) p = sl * 0.5 b = sl * math.cos(math.radians(30)) w = b * 2 h = 2 * sl startx = startx - w starty = starty - h endx = endx + w endy = endy + h origx = startx origy = starty xoffset = b yoffset = 3 * p polygons = [] row = 1 counter = 0 while starty < endy: if row % 2 == 0: startx = origx + xoffset else: startx = origx while startx < endx: p1x = startx p1y = starty + p p2x = startx p2y = starty + (3 * p) p3x = startx + b p3y = starty + h p4x = startx + w p4y = starty + (3 * p) p5x = startx + w p5y = starty + p p6x = startx + b p6y = starty poly = [ (p1x, p1y), (p2x, p2y), (p3x, p3y), (p4x, p4y), (p5x, p5y), (p6x, p6y), (p1x, p1y)] polygons.append(poly) counter += 1 startx += w starty += yoffset row += 1 return polygons
Write a function to convert the given binary tuple to integer.
def binary_to_integer(test_tup): res = int("".join(str(ele) for ele in test_tup), 2) return (str(res))
Write a function to remove lowercase substrings from a given string by using regex.
import re def remove_lowercase(str1): remove_lower = lambda text: re.sub('[a-z]', '', text) result = remove_lower(str1) return (result)
Write a function to find the smallest integers from a given list of numbers using heap queue algorithm.
import heapq as hq def heap_queue_smallest(nums,n): smallest_nums = hq.nsmallest(n, nums) return smallest_nums
Write a function to find the surface area of a cone.
import math def surfacearea_cone(r,h): l = math.sqrt(r * r + h * h) SA = math.pi * r * (r + l) return SA
Write a python function to find gcd of two positive integers.
def gcd(x, y): gcd = 1 if x % y == 0: return y for k in range(int(y / 2), 0, -1): if x % k == 0 and y % k == 0: gcd = k break return gcd
Write a function to find the diameter of a circle.
def diameter_circle(r): diameter=2*r return diameter
Write a function to concatenate all elements of the given list into a string.
def concatenate_elements(list): ans = ' ' for i in list: ans = ans+ ' '+i return (ans)
Write a python function to find common divisor between two numbers in a given pair.
def ngcd(x,y): i=1 while(i<=x and i<=y): if(x%i==0 and y%i == 0): gcd=i; i+=1 return gcd; def num_comm_div(x,y): n = ngcd(x,y) result = 0 z = int(n**0.5) i = 1 while(i <= z): if(n % i == 0): result += 2 if(i == n/i): result-=1 i+=1 return result
Write a python function to find remainder of two numbers.
def find(n,m): r = n%m return (r)
Write a function to add consecutive numbers of a given list.
def add_consecutive_nums(nums): result = [b+a for a, b in zip(nums[:-1], nums[1:])] return result
Write a python function to find the cube sum of first n natural numbers.
def sum_Of_Series(n): sum = 0 for i in range(1,n + 1): sum += i * i*i return sum
Write a function to move all zeroes to the end of the given array.
def re_order(A): k = 0 for i in A: if i: A[k] = i k = k + 1 for i in range(k, len(A)): A[i] = 0 return A
Write a function to calculate the permutation coefficient of given p(n, k).
def permutation_coefficient(n, k): P = [[0 for i in range(k + 1)] for j in range(n + 1)] for i in range(n + 1): for j in range(min(i, k) + 1): if (j == 0): P[i][j] = 1 else: P[i][j] = P[i - 1][j] + ( j * P[i - 1][j - 1]) if (j < k): P[i][j + 1] = 0 return P[n][k]
Write a function to remove specific words from a given list.
def remove_words(list1, removewords): for word in list(list1): if word in removewords: list1.remove(word) return list1
Write a function to check if the common elements between two given lists are in the same order or not.
def same_order(l1, l2): common_elements = set(l1) & set(l2) l1 = [e for e in l1 if e in common_elements] l2 = [e for e in l2 if e in common_elements] return l1 == l2
Write a python function to find the average of odd numbers till a given odd number.
def average_Odd(n) : if (n%2==0) : return ("Invalid Input") return -1 sm =0 count =0 while (n>=1) : count=count+1 sm = sm + n n = n-2 return sm//count
Write a function to find the number of subsequences having product smaller than k for the given non negative array.
def no_of_subsequences(arr, k): n = len(arr) dp = [[0 for i in range(n + 1)] for j in range(k + 1)] for i in range(1, k + 1): for j in range(1, n + 1): dp[i][j] = dp[i][j - 1] if arr[j - 1] <= i and arr[j - 1] > 0: dp[i][j] += dp[i // arr[j - 1]][j - 1] + 1 return dp[k][n]