question
stringlengths
37
191
answer
stringlengths
37
1.33k
Write a python function to set the left most unset bit.
def set_left_most_unset_bit(n): if not (n & (n + 1)): return n pos, temp, count = 0, n, 0 while temp: if not (temp & 1): pos = count count += 1; temp>>=1 return (n | (1 << (pos)))
Write a function to find the volume of a cone.
import math def volume_cone(r,h): volume = (1.0/3) * math.pi * r * r * h return volume
Write a python function to print positive numbers in a list.
def pos_nos(list1): for num in list1: if num >= 0: return num
Write a function to find out the maximum sum such that no two chosen numbers are adjacent for the given rectangular grid of dimension 2 x n.
def max_sum_rectangular_grid(grid, n) : incl = max(grid[0][0], grid[1][0]) excl = 0 for i in range(1, n) : excl_new = max(excl, incl) incl = excl + max(grid[0][i], grid[1][i]) excl = excl_new return max(excl, incl)
Write a python function to find the first maximum length of even word.
def find_Max_Len_Even(str): n = len(str) i = 0 currlen = 0 maxlen = 0 st = -1 while (i < n): if (str[i] == ' '): if (currlen % 2 == 0): if (maxlen < currlen): maxlen = currlen st = i - currlen currlen = 0 else : currlen += 1 i += 1 if (currlen % 2 == 0): if (maxlen < currlen): maxlen = currlen st = i - currlen if (st == -1): return "-1" return str[st: st + maxlen]
Write a function to find the index of the last occurrence of a given number in a sorted array.
def find_last_occurrence(A, x): (left, right) = (0, len(A) - 1) result = -1 while left <= right: mid = (left + right) // 2 if x == A[mid]: result = mid left = mid + 1 elif x < A[mid]: right = mid - 1 else: left = mid + 1 return result
Write a function to reflect the modified run-length encoding from a list.
from itertools import groupby def modified_encode(alist): def ctr_ele(el): if len(el)>1: return [len(el), el[0]] else: return el[0] return [ctr_ele(list(group)) for key, group in groupby(alist)]
Write a python function to find the maximum volume of a cuboid with given sum of sides.
def max_volume (s): maxvalue = 0 i = 1 for i in range(s - 1): j = 1 for j in range(s): k = s - i - j maxvalue = max(maxvalue, i * j * k) return maxvalue
Write a function to find all five characters long word in the given string by using regex.
import re def find_long_word(text): return (re.findall(r"\b\w{5}\b", text))
Write a function to calculate the difference between the squared sum of first n natural numbers and the sum of squared first n natural numbers.
def sum_difference(n): sumofsquares = 0 squareofsum = 0 for num in range(1, n+1): sumofsquares += num * num squareofsum += num squareofsum = squareofsum ** 2 return squareofsum - sumofsquares
Write a function to find the demlo number for the given number.
def find_demlo(s): l = len(s) res = "" for i in range(1,l+1): res = res + str(i) for i in range(l-1,0,-1): res = res + str(i) return res
Write a function to find all index positions of the minimum values in a given list.
def position_min(list1): min_val = min(list1) min_result = [i for i, j in enumerate(list1) if j == min_val] return min_result
Write a function to re-arrange the given array in alternating positive and negative items.
def right_rotate(arr, n, out_of_place, cur): temp = arr[cur] for i in range(cur, out_of_place, -1): arr[i] = arr[i - 1] arr[out_of_place] = temp return arr def re_arrange(arr, n): out_of_place = -1 for index in range(n): if (out_of_place >= 0): if ((arr[index] >= 0 and arr[out_of_place] < 0) or (arr[index] < 0 and arr[out_of_place] >= 0)): arr = right_rotate(arr, n, out_of_place, index) if (index-out_of_place > 2): out_of_place += 2 else: out_of_place = - 1 if (out_of_place == -1): if ((arr[index] >= 0 and index % 2 == 0) or (arr[index] < 0 and index % 2 == 1)): out_of_place = index return arr
Write a function to extract the sum of alternate chains of tuples.
def sum_of_alternates(test_tuple): sum1 = 0 sum2 = 0 for idx, ele in enumerate(test_tuple): if idx % 2: sum1 += ele else: sum2 += ele return ((sum1),(sum2))
Write a python function to find the minimum number of squares whose sum is equal to a given number.
def get_Min_Squares(n): if n <= 3: return n; res = n for x in range(1,n + 1): temp = x * x; if temp > n: break else: res = min(res,1 + get_Min_Squares(n - temp)) return res;
Write a function to get the word with most number of occurrences in the given strings list.
from collections import defaultdict def most_occurrences(test_list): temp = defaultdict(int) for sub in test_list: for wrd in sub.split(): temp[wrd] += 1 res = max(temp, key=temp.get) return (str(res))
Write a function to print check if the triangle is isosceles or not.
def check_isosceles(x,y,z): if x==y or y==z or z==x: return True else: return False
Write a function to rotate a given list by specified number of items to the left direction.
def rotate_left(list1,m,n): result = list1[m:]+list1[:n] return result
Write a python function to count negative numbers in a list.
def neg_count(list): neg_count= 0 for num in list: if num <= 0: neg_count += 1 return neg_count
Write a function to find all three, four, five characters long words in the given string by using regex.
import re def find_char(text): return (re.findall(r"\b\w{3,5}\b", text))
Write a python function to count unset bits of a given number.
def count_unset_bits(n): count = 0 x = 1 while(x < n + 1): if ((x & n) == 0): count += 1 x = x << 1 return count
Write a function to count character frequency of a given string.
def char_frequency(str1): dict = {} for n in str1: keys = dict.keys() if n in keys: dict[n] += 1 else: dict[n] = 1 return dict
Write a python function to sort a list according to the second element in sublist.
def Sort(sub_li): sub_li.sort(key = lambda x: x[1]) return sub_li
Write a python function to check whether the triangle is valid or not if sides are given.
def check_Validity(a,b,c): if (a + b <= c) or (a + c <= b) or (b + c <= a) : return False else: return True
Write a function to find the sum of arithmetic progression.
def ap_sum(a,n,d): total = (n * (2 * a + (n - 1) * d)) / 2 return total
Write a function to check whether the given month name contains 28 days or not.
def check_monthnum(monthname1): if monthname1 == "February": return True else: return False
Write a function that matches a word at the end of a string, with optional punctuation.
import re def text_match_word(text): patterns = '\w+\S*$' if re.search(patterns, text): return 'Found a match!' else: return 'Not matched!'
Write a python function to count the number of substrings with same first and last characters.
def check_Equality(s): return (ord(s[0]) == ord(s[len(s) - 1])); def count_Substring_With_Equal_Ends(s): result = 0; n = len(s); for i in range(n): for j in range(1,n-i+1): if (check_Equality(s[i:i+j])): result+=1; return result;
Write a python function to find the maximum occuring divisor in an interval.
def find_Divisor(x,y): if (x==y): return y return 2
Write a python function to find the sum of the three lowest positive numbers from a given list of numbers.
def sum_three_smallest_nums(lst): return sum(sorted([x for x in lst if x > 0])[:3])
Write a function to convert the given set into ordered tuples.
def set_to_tuple(s): t = tuple(sorted(s)) return (t)
Write a function to find the smallest range that includes at-least one element from each of the given arrays.
from heapq import heappop, heappush class Node: def __init__(self, value, list_num, index): self.value = value self.list_num = list_num self.index = index def __lt__(self, other): return self.value < other.value def find_minimum_range(list): high = float('-inf') p = (0, float('inf')) pq = [] for i in range(len(list)): heappush(pq, Node(list[i][0], i, 0)) high = max(high, list[i][0]) while True: top = heappop(pq) low = top.value i = top.list_num j = top.index if high - low < p[1] - p[0]: p = (low, high) if j == len(list[i]) - 1: return p heappush(pq, Node(list[i][j + 1], i, j + 1)) high = max(high, list[i][j + 1])
Write a function to calculate the number of digits and letters in a string.
def dig_let(s): d=l=0 for c in s: if c.isdigit(): d=d+1 elif c.isalpha(): l=l+1 else: pass return (l,d)
Write a python function to find number of elements with odd factors in a given range.
def count_Odd_Squares(n,m): return int(m**0.5) - int((n-1)**0.5)
Write a function to find the difference between two consecutive numbers in a given list.
def diff_consecutivenums(nums): result = [b-a for a, b in zip(nums[:-1], nums[1:])] return result
Write a function to find entringer number e(n, k).
def zigzag(n, k): if (n == 0 and k == 0): return 1 if (k == 0): return 0 return zigzag(n, k - 1) + zigzag(n - 1, n - k)
Write a python function to count the number of squares in a rectangle.
def count_Squares(m,n): if (n < m): temp = m m = n n = temp return n * (n + 1) * (3 * m - n + 1) // 6
Write a function to count sequences of given length having non-negative prefix sums that can be generated by given values.
def bin_coff(n, r): val = 1 if (r > (n - r)): r = (n - r) for i in range(0, r): val *= (n - i) val //= (i + 1) return val def find_ways(M): n = M // 2 a = bin_coff(2 * n, n) b = a // (n + 1) return (b)
Write a python function to check whether the given string is a binary string or not.
def check(string) : p = set(string) s = {'0', '1'} if s == p or p == {'0'} or p == {'1'}: return ("Yes") else : return ("No")
Write a python function to minimize the length of the string by removing occurrence of only one character.
def minimum_Length(s) : maxOcc = 0 n = len(s) arr = [0]*26 for i in range(n) : arr[ord(s[i]) -ord('a')] += 1 for i in range(26) : if arr[i] > maxOcc : maxOcc = arr[i] return n - maxOcc
Write a python function to find the first element occurring k times in a given array.
def first_Element(arr,n,k): count_map = {}; for i in range(0, n): if(arr[i] in count_map.keys()): count_map[arr[i]] += 1 else: count_map[arr[i]] = 1 i += 1 for i in range(0, n): if (count_map[arr[i]] == k): return arr[i] i += 1 return -1
Write a python function to check whether all the characters in a given string are unique.
def unique_Characters(str): for i in range(len(str)): for j in range(i + 1,len(str)): if (str[i] == str[j]): return False; return True;
Write a function to remove a specified column from a given nested list.
def remove_column(list1, n): for i in list1: del i[n] return list1
Write a function to find t-nth term of arithemetic progression.
def tn_ap(a,n,d): tn = a + (n - 1) * d return tn
Write a python function to count the number of rectangles in a circle of radius r.
def count_Rectangles(radius): rectangles = 0 diameter = 2 * radius diameterSquare = diameter * diameter for a in range(1, 2 * radius): for b in range(1, 2 * radius): diagnalLengthSquare = (a * a + b * b) if (diagnalLengthSquare <= diameterSquare) : rectangles += 1 return rectangles
Write a function to find the third angle of a triangle using two angles.
def find_angle(a,b): c = 180 - (a + b) return c
Write a function to find the maximum element of all the given tuple records.
def find_max(test_list): res = max(int(j) for i in test_list for j in i) return (res)
Write a function to find modulo division of two lists using map and lambda function.
def moddiv_list(nums1,nums2): result = map(lambda x, y: x % y, nums1, nums2) return list(result)
Write a python function to check whether one root of the quadratic equation is twice of the other or not.
def Check_Solution(a,b,c): if (2*b*b == 9*a*c): return ("Yes"); else: return ("No");
Write a function to find the n’th carol number.
def get_carol(n): result = (2**n) - 1 return result * result - 2
Write a function to remove empty lists from a given list of lists.
def remove_empty(list1): remove_empty = [x for x in list1 if x] return remove_empty
Write a python function to find the item with maximum occurrences in a given list.
def max_occurrences(nums): max_val = 0 result = nums[0] for i in nums: occu = nums.count(i) if occu > max_val: max_val = occu result = i return result
Write a function to add the k elements to each element in the tuple.
def add_K_element(test_list, K): res = [tuple(j + K for j in sub ) for sub in test_list] return (res)
Write a function to find the number of flips required to make the given binary string a sequence of alternate characters.
def make_flip(ch): return '1' if (ch == '0') else '0' def get_flip_with_starting_charcter(str, expected): flip_count = 0 for i in range(len( str)): if (str[i] != expected): flip_count += 1 expected = make_flip(expected) return flip_count def min_flip_to_make_string_alternate(str): return min(get_flip_with_starting_charcter(str, '0'),get_flip_with_starting_charcter(str, '1'))
Write a python function to count the number of digits of a given number.
def count_Digit(n): count = 0 while n != 0: n //= 10 count += 1 return count
Write a python function to find the largest product of the pair of adjacent elements from a given list of integers.
def adjacent_num_product(list_nums): return max(a*b for a, b in zip(list_nums, list_nums[1:]))
Write a function to check if a binary tree is balanced or not.
class Node: def __init__(self, data): self.data = data self.left = None self.right = None def get_height(root): if root is None: return 0 return max(get_height(root.left), get_height(root.right)) + 1 def is_tree_balanced(root): if root is None: return True lh = get_height(root.left) rh = get_height(root.right) if (abs(lh - rh) <= 1) and is_tree_balanced( root.left) is True and is_tree_balanced( root.right) is True: return True return False
Write a function to repeat the given tuple n times.
def repeat_tuples(test_tup, N): res = ((test_tup, ) * N) return (res)
Write a function to find the lateral surface area of cuboid
def lateralsurface_cuboid(l,w,h): LSA = 2*h*(l+w) return LSA
Write a function to sort a tuple by its float element.
def float_sort(price): float_sort=sorted(price, key=lambda x: float(x[1]), reverse=True) return float_sort
Write a function to find the smallest missing element in a sorted array.
def smallest_missing(A, left_element, right_element): if left_element > right_element: return left_element mid = left_element + (right_element - left_element) // 2 if A[mid] == mid: return smallest_missing(A, mid + 1, right_element) else: return smallest_missing(A, left_element, mid - 1)
Write a function to sort a given list of elements in ascending order using heap queue algorithm.
import heapq as hq def heap_assending(nums): hq.heapify(nums) s_result = [hq.heappop(nums) for i in range(len(nums))] return s_result
Write a function to find the volume of a cuboid.
def volume_cuboid(l,w,h): volume=l*w*h return volume
Write a function to print all permutations of a given string including duplicates.
def permute_string(str): if len(str) == 0: return [''] prev_list = permute_string(str[1:len(str)]) next_list = [] for i in range(0,len(prev_list)): for j in range(0,len(str)): new_str = prev_list[i][0:j]+str[0]+prev_list[i][j:len(str)-1] if new_str not in next_list: next_list.append(new_str) return next_list
Write a function to round the given number to the nearest multiple of a specific number.
def round_num(n,m): a = (n //m) * m b = a + m return (b if n - a > b - n else a)
Write a function to remove tuple elements that occur more than once and replace the duplicates with some custom value.
def remove_replica(test_tup): temp = set() res = tuple(ele if ele not in temp and not temp.add(ele) else 'MSP' for ele in test_tup) return (res)
Write a python function to remove all occurrences of a character in a given string.
def remove_Char(s,c) : counts = s.count(c) s = list(s) while counts : s.remove(c) counts -= 1 s = '' . join(s) return (s)
Write a python function to shift last element to first position in the given list.
def move_first(test_list): test_list = test_list[-1:] + test_list[:-1] return test_list
Write a function to find the surface area of a cuboid.
def surfacearea_cuboid(l,w,h): SA = 2*(l*w + l * h + w * h) return SA
Write a function to generate a two-dimensional array.
def multi_list(rownum,colnum): multi_list = [[0 for col in range(colnum)] for row in range(rownum)] for row in range(rownum): for col in range(colnum): multi_list[row][col]= row*col return multi_list
Write a function to sort a list of lists by a given index of the inner list.
from operator import itemgetter def index_on_inner_list(list_data, index_no): result = sorted(list_data, key=itemgetter(index_no)) return result
Write a function to find the number of rotations in a circularly sorted array.
def find_rotation_count(A): (left, right) = (0, len(A) - 1) while left <= right: if A[left] <= A[right]: return left mid = (left + right) // 2 next = (mid + 1) % len(A) prev = (mid - 1 + len(A)) % len(A) if A[mid] <= A[next] and A[mid] <= A[prev]: return mid elif A[mid] <= A[right]: right = mid - 1 elif A[mid] >= A[left]: left = mid + 1 return -1
Write a python function to toggle all odd bits of a given number.
def even_bit_toggle_number(n) : res = 0; count = 0; temp = n while(temp > 0 ) : if (count % 2 == 0) : res = res | (1 << count) count = count + 1 temp >>= 1 return n ^ res
Write a python function to find the frequency of the smallest value in a given array.
def frequency_Of_Smallest(n,arr): mn = arr[0] freq = 1 for i in range(1,n): if (arr[i] < mn): mn = arr[i] freq = 1 elif (arr[i] == mn): freq += 1 return freq
Write a function to find the n'th perrin number using recursion.
def get_perrin(n): if (n == 0): return 3 if (n == 1): return 0 if (n == 2): return 2 return get_perrin(n - 2) + get_perrin(n - 3)
Write a function to find out the minimum no of swaps required for bracket balancing in the given string.
def swap_count(s): chars = s count_left = 0 count_right = 0 swap = 0 imbalance = 0; for i in range(len(chars)): if chars[i] == '[': count_left += 1 if imbalance > 0: swap += imbalance imbalance -= 1 elif chars[i] == ']': count_right += 1 imbalance = (count_right - count_left) return swap
Write a python function to check whether the hexadecimal number is even or odd.
def even_or_odd(N): l = len(N) if (N[l-1] =='0'or N[l-1] =='2'or N[l-1] =='4'or N[l-1] =='6'or N[l-1] =='8'or N[l-1] =='A'or N[l-1] =='C'or N[l-1] =='E'): return ("Even") else: return ("Odd")
Write a python function to find the highest power of 2 that is less than or equal to n.
def highest_Power_of_2(n): res = 0; for i in range(n, 0, -1): if ((i & (i - 1)) == 0): res = i; break; return res;
Write a function to find the n'th lucas number.
def find_lucas(n): if (n == 0): return 2 if (n == 1): return 1 return find_lucas(n - 1) + find_lucas(n - 2)
Write a function to insert a given string at the beginning of all items in a list.
def add_string(list,string): add_string=[string.format(i) for i in list] return add_string
Write a function to convert more than one list to nested dictionary.
def convert_list_dictionary(l1, l2, l3): result = [{x: {y: z}} for (x, y, z) in zip(l1, l2, l3)] return result
Write a function to find the maximum sum possible by using the given equation f(n) = max( (f(n/2) + f(n/3) + f(n/4) + f(n/5)), n).
def get_max_sum (n): res = list() res.append(0) res.append(1) i = 2 while i<n + 1: res.append(max(i, (res[int(i / 2)] + res[int(i / 3)] + res[int(i / 4)] + res[int(i / 5)]))) i = i + 1 return res[n]
Write a function to find the list with maximum length using lambda function.
def max_length_list(input_list): max_length = max(len(x) for x in input_list ) max_list = max(input_list, key = lambda i: len(i)) return(max_length, max_list)
Write a function to check if given tuple is distinct or not.
def check_distinct(test_tup): res = True temp = set() for ele in test_tup: if ele in temp: res = False break temp.add(ele) return (res)
Write a python function to find the first non-repeated character in a given string.
def first_non_repeating_character(str1): char_order = [] ctr = {} for c in str1: if c in ctr: ctr[c] += 1 else: ctr[c] = 1 char_order.append(c) for c in char_order: if ctr[c] == 1: return c return None
Write a function to check whether the given string starts and ends with the same character or not using regex.
import re regex = r'^[a-z]$|^([a-z]).*\1$' def check_char(string): if(re.search(regex, string)): return "Valid" else: return "Invalid"
Write a function to find the median of three specific numbers.
def median_numbers(a,b,c): if a > b: if a < c: median = a elif b > c: median = b else: median = c else: if a > c: median = a elif b < c: median = b else: median = c return median
Write a function to compute the sum of digits of each number of a given list.
def sum_of_digits(nums): return sum(int(el) for n in nums for el in str(n) if el.isdigit())
Write a function to perform the mathematical bitwise xor operation across the given tuples.
def bitwise_xor(test_tup1, test_tup2): res = tuple(ele1 ^ ele2 for ele1, ele2 in zip(test_tup1, test_tup2)) return (res)
Write a function to extract the frequency of unique tuples in the given list order irrespective.
def extract_freq(test_list): res = len(list(set(tuple(sorted(sub)) for sub in test_list))) return (res)
Write a function to perform index wise addition of tuple elements in the given two nested tuples.
def add_nested_tuples(test_tup1, test_tup2): res = tuple(tuple(a + b for a, b in zip(tup1, tup2)) for tup1, tup2 in zip(test_tup1, test_tup2)) return (res)
Write a function to compute the value of ncr%p.
def ncr_modp(n, r, p): C = [0 for i in range(r+1)] C[0] = 1 for i in range(1, n+1): for j in range(min(i, r), 0, -1): C[j] = (C[j] + C[j-1]) % p return C[r]
Write a function to check if a url is valid or not using regex.
import re def is_valid_URL(str): regex = ("((http|https)://)(www.)?" + "[a-zA-Z0-9@:%._\\+~#?&//=]" + "{2,256}\\.[a-z]" + "{2,6}\\b([-a-zA-Z0-9@:%" + "._\\+~#?&//=]*)") p = re.compile(regex) if (str == None): return False if(re.search(p, str)): return True else: return False
Write a python function to find the minimum of two numbers.
def minimum(a,b): if a <= b: return a else: return b
Write a function to check whether an element exists within a tuple.
def check_tuplex(tuplex,tuple1): if tuple1 in tuplex: return True else: return False
Write a python function to find the parity of a given number.
def find_Parity(x): y = x ^ (x >> 1); y = y ^ (y >> 2); y = y ^ (y >> 4); y = y ^ (y >> 8); y = y ^ (y >> 16); if (y & 1): return ("Odd Parity"); return ("Even Parity");
Write a function to create the next bigger number by rearranging the digits of a given number.
def rearrange_bigger(n): nums = list(str(n)) for i in range(len(nums)-2,-1,-1): if nums[i] < nums[i+1]: z = nums[i:] y = min(filter(lambda x: x > z[0], z)) z.remove(y) z.sort() nums[i:] = [y] + z return int("".join(nums)) return False
Write a function to find k number of pairs which consist of one element from the first array and one element from the second array.
import heapq def k_smallest_pairs(nums1, nums2, k): queue = [] def push(i, j): if i < len(nums1) and j < len(nums2): heapq.heappush(queue, [nums1[i] + nums2[j], i, j]) push(0, 0) pairs = [] while queue and len(pairs) < k: _, i, j = heapq.heappop(queue) pairs.append([nums1[i], nums2[j]]) push(i, j + 1) if j == 0: push(i + 1, 0) return pairs
Write a function to find the minimum product from the pairs of tuples within a given list.
def min_product_tuple(list1): result_min = min([abs(x * y) for x, y in list1] ) return result_min
Write a function to find the minimum value in a given heterogeneous list.
def min_val(listval): min_val = min(i for i in listval if isinstance(i, int)) return min_val