codeparrot/xlcost-text-to-code huggingface dataset:
Find ( a ^ b ) % m where ' a ' is very large | Python program to find ( a ^ b ) mod m for a large 'a ; utility function to calculate a % m ; convert string s [ i ] to integer which gives the digit value and form the number ; Returns find ( a ^ b ) % m ; Find a % m ; now multiply ans by b - 1 times and take mod with m ; Driver program to run the case
' NEW_LINE def aModM ( s , mod ) : NEW_LINE INDENT number = 0 NEW_LINE for i in range ( len ( s ) ) : NEW_LINE INDENT number = ( number * 10 + int ( s [ i ] ) ) NEW_LINE number = number % m NEW_LINE DEDENT return number NEW_LINE DEDENT def ApowBmodM ( a , b , m ) : NEW_LINE INDENT ans = aModM ( a , m ) NEW_LINE mul = ans NEW_LINE for i in range ( 1 , b ) : NEW_LINE INDENT ans = ( ans * mul ) % m NEW_LINE DEDENT return ans NEW_LINE DEDENT a = "987584345091051645734583954832576" NEW_LINE b , m = 3 , 11 NEW_LINE print ApowBmodM ( a , b , m ) NEW_LINE
Lagrange 's Interpolation | To represent a data point corresponding to x and y = f ( x ) ; function to interpolate the given data points using Lagrange 's formula xi -> corresponds to the new data point whose value is to be obtained n -> represents the number of known data points ; Initialize result ; Compute individual terms of above formula ; Add current term to result ; Driver Code ; creating an array of 4 known data points ; Using the interpolate function to obtain a data point corresponding to x = 3
class Data : NEW_LINE INDENT def __init__ ( self , x , y ) : NEW_LINE INDENT self . x = x NEW_LINE self . y = y NEW_LINE DEDENT DEDENT def interpolate ( f : list , xi : int , n : int ) -> float : NEW_LINE INDENT result = 0.0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT term = f [ i ] . y NEW_LINE for j in range ( n ) : NEW_LINE INDENT if j != i : NEW_LINE INDENT term = term * ( xi - f [ j ] . x ) / ( f [ i ] . x - f [ j ] . x ) NEW_LINE DEDENT DEDENT result += term NEW_LINE DEDENT return result NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT f = [ Data ( 0 , 2 ) , Data ( 1 , 3 ) , Data ( 2 , 12 ) , Data ( 5 , 147 ) ] NEW_LINE print ( " Value ▁ of ▁ f ( 3 ) ▁ is ▁ : " , interpolate ( f , 3 , 4 ) ) NEW_LINE DEDENT
Sieve of Sundaram to print all primes smaller than n | Prints all prime numbers smaller ; In general Sieve of Sundaram , produces primes smaller than ( 2 * x + 2 ) for a number given number x . Since we want primes smaller than n , we reduce n to half ; This array is used to separate numbers of the form i + j + 2 ij from others where 1 <= i <= j Initialize all elements as not marked ; Main logic of Sundaram . Mark all numbers of the form i + j + 2 ij as true where 1 <= i <= j ; Since 2 is a prime number ; Print other primes . Remaining primes are of the form 2 * i + 1 such that marked [ i ] is false . ; Driver Code
def SieveOfSundaram ( n ) : NEW_LINE INDENT nNew = int ( ( n - 1 ) / 2 ) ; NEW_LINE marked = [ 0 ] * ( nNew + 1 ) ; NEW_LINE for i in range ( 1 , nNew + 1 ) : NEW_LINE INDENT j = i ; NEW_LINE while ( ( i + j + 2 * i * j ) <= nNew ) : NEW_LINE INDENT marked [ i + j + 2 * i * j ] = 1 ; NEW_LINE j += 1 ; NEW_LINE DEDENT DEDENT if ( n > 2 ) : NEW_LINE INDENT print ( 2 , end = " ▁ " ) ; NEW_LINE DEDENT for i in range ( 1 , nNew + 1 ) : NEW_LINE INDENT if ( marked [ i ] == 0 ) : NEW_LINE INDENT print ( ( 2 * i + 1 ) , end = " ▁ " ) ; NEW_LINE DEDENT DEDENT DEDENT n = 20 ; NEW_LINE SieveOfSundaram ( n ) ; NEW_LINE
Construct original array starting with K from an array of XOR of all elements except elements at same index | Function to construct an array with each element equal to XOR of all array elements except the element at the same index ; Original array ; Stores Bitwise XOR of array ; Calculate XOR of all array elements ; Print the original array B ; Driver Code ; Function Call
def constructArray ( A , N , K ) : NEW_LINE INDENT B = [ 0 ] * N ; NEW_LINE totalXOR = A [ 0 ] ^ K ; NEW_LINE for i in range ( N ) : NEW_LINE INDENT B [ i ] = totalXOR ^ A [ i ] ; NEW_LINE DEDENT for i in range ( N ) : NEW_LINE INDENT print ( B [ i ] , end = " ▁ " ) ; NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT A = [ 13 , 14 , 10 , 6 ] ; NEW_LINE K = 2 ; NEW_LINE N = len ( A ) ; NEW_LINE constructArray ( A , N , K ) ; NEW_LINE DEDENT
Find extra element in the second array | Function to return the extra element in B [ ] ; To store the result ; Find the XOR of all the element of array A [ ] and array B [ ] ; Driver code
def extraElement ( A , B , n ) : NEW_LINE INDENT ans = 0 ; NEW_LINE for i in range ( n ) : NEW_LINE INDENT ans ^= A [ i ] ; NEW_LINE DEDENT for i in range ( n + 1 ) : NEW_LINE INDENT ans ^= B [ i ] ; NEW_LINE DEDENT return ans ; NEW_LINE DEDENT A = [ 10 , 15 , 5 ] ; NEW_LINE B = [ 10 , 100 , 15 , 5 ] ; NEW_LINE n = len ( A ) ; NEW_LINE print ( extraElement ( A , B , n ) ) ; NEW_LINE
Hamming distance between two Integers | Function to calculate hamming distance ; Driver code
def hammingDistance ( n1 , n2 ) : NEW_LINE INDENT x = n1 ^ n2 NEW_LINE setBits = 0 NEW_LINE while ( x > 0 ) : NEW_LINE INDENT setBits += x & 1 NEW_LINE x >>= 1 NEW_LINE DEDENT return setBits NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT n1 = 9 NEW_LINE n2 = 14 NEW_LINE print ( hammingDistance ( 9 , 14 ) ) NEW_LINE DEDENT
Print bitwise AND set of a number N | function to find bitwise subsets Naive approach ; Driver code
def printSubsets ( n ) : NEW_LINE INDENT for i in range ( n + 1 ) : NEW_LINE INDENT if ( ( n & i ) == i ) : NEW_LINE INDENT print ( i , " ▁ " , end = " " ) NEW_LINE DEDENT DEDENT DEDENT n = 9 NEW_LINE printSubsets ( n ) NEW_LINE
Find most significant set bit of a number | Python program to find MSB number for given n . ; To find the position of the most significant set bit ; To return the value of the number with set bit at k - th position ; Driver code
import math NEW_LINE def setBitNumber ( n ) : NEW_LINE INDENT k = int ( math . log ( n , 2 ) ) NEW_LINE return 1 << k NEW_LINE DEDENT n = 273 NEW_LINE print ( setBitNumber ( n ) ) NEW_LINE
Minimum number of subsets with distinct elements | function to count subsets such that all subsets have distinct elements . ; take input and initialize res = 0 ; sort the array ; traverse the input array and find maximum frequency ; for each number find its repetition / frequency ; update res ; Driver code
def subset ( ar , n ) : NEW_LINE INDENT res = 0 NEW_LINE ar . sort ( ) NEW_LINE for i in range ( 0 , n ) : NEW_LINE INDENT count = 1 NEW_LINE for i in range ( n - 1 ) : NEW_LINE INDENT if ar [ i ] == ar [ i + 1 ] : NEW_LINE INDENT count += 1 NEW_LINE DEDENT else : NEW_LINE INDENT break NEW_LINE DEDENT DEDENT res = max ( res , count ) NEW_LINE DEDENT return res NEW_LINE DEDENT ar = [ 5 , 6 , 9 , 3 , 4 , 3 , 4 ] NEW_LINE n = len ( ar ) NEW_LINE print ( subset ( ar , n ) ) NEW_LINE
Minimum number of subsets with distinct elements | Function to count subsets such that all subsets have distinct elements . ; Traverse the input array and store frequencies of elements ; Find the maximum value in map . ; Driver code
def subset ( arr , n ) : NEW_LINE INDENT mp = { i : 0 for i in range ( 10 ) } NEW_LINE for i in range ( n ) : NEW_LINE INDENT mp [ arr [ i ] ] += 1 NEW_LINE DEDENT res = 0 NEW_LINE for key , value in mp . items ( ) : NEW_LINE INDENT res = max ( res , value ) NEW_LINE DEDENT return res NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 5 , 6 , 9 , 3 , 4 , 3 , 4 ] NEW_LINE n = len ( arr ) NEW_LINE print ( subset ( arr , n ) ) NEW_LINE DEDENT
Count ways to represent a number as sum of perfect squares | ''Store perfect squares less than or equal to N ; ''Utility function to calculate perfect squares less than or equal to N ; ''Function to find the number of ways to represent a number as sum of perfect squares ; '' Handle the base cases ; '' Include the i-th index element ; '' Exclude the i-th index element ; '' Return the result ; ''Driver Code ; '' Given Input ; '' Precalculate perfect  squares <= N ; '' Function Call
psquare = [ ] NEW_LINE def calcPsquare ( N ) : NEW_LINE INDENT for i in range ( 1 , N ) : NEW_LINE INDENT if i * i > N : NEW_LINE INDENT break NEW_LINE DEDENT psquare . append ( i * i ) NEW_LINE DEDENT DEDENT def countWays ( index , target ) : NEW_LINE INDENT if ( target == 0 ) : NEW_LINE INDENT return 1 NEW_LINE DEDENT if ( index < 0 or target < 0 ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT inc = countWays ( index , target - psquare [ index ] ) NEW_LINE exc = countWays ( index - 1 , target ) NEW_LINE return inc + exc NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 9 NEW_LINE calcPsquare ( N ) NEW_LINE print ( countWays ( len ( psquare ) - 1 , N ) ) NEW_LINE DEDENT
Sum of distances of all nodes from a given node | ''Stores the sum of distances of all nodes from the given node ; ''Structure of a binary tree node ; ''Function to count the number of nodes in the left and right subtrees ; '' Initialize a pair that stores  the pair {number of nodes, depth} ; '' Finding the number of nodes  in the left subtree ; '' Find the number of nodes  in the right subtree ; '' Filling up size field ; ''Function to find the total distance ; '' If target node matches with  the current node ; '' If root.left is not null ; '' Update sum ; '' Recur for the left subtree ; '' If root.right is not null ; '' Apply the formula given  in the approach ; '' Recur for the right subtree ; ''Driver Code ; '' Input tree ; '' Total number of nodes ; '' Print the sum of distances
sum = 0 NEW_LINE class TreeNode : NEW_LINE INDENT def __init__ ( self , data ) : NEW_LINE INDENT self . data = data NEW_LINE self . size = 0 NEW_LINE self . left = None NEW_LINE self . right = None NEW_LINE DEDENT DEDENT def sumofsubtree ( root ) : NEW_LINE INDENT p = [ 1 , 0 ] NEW_LINE if ( root . left ) : NEW_LINE INDENT ptemp = sumofsubtree ( root . left ) NEW_LINE p [ 1 ] += ptemp [ 0 ] + ptemp [ 1 ] NEW_LINE p [ 0 ] += ptemp [ 0 ] NEW_LINE DEDENT if ( root . right ) : NEW_LINE INDENT ptemp = sumofsubtree ( root . right ) NEW_LINE p [ 1 ] += ptemp [ 0 ] + ptemp [ 1 ] NEW_LINE p [ 0 ] += ptemp [ 0 ] NEW_LINE DEDENT root . size = p [ 0 ] NEW_LINE return p NEW_LINE DEDENT def distance ( root , target , distancesum , n ) : NEW_LINE INDENT global sum NEW_LINE if ( root . data == target ) : NEW_LINE INDENT sum = distancesum NEW_LINE DEDENT if ( root . left ) : NEW_LINE INDENT tempsum = ( distancesum - root . left . size + ( n - root . left . size ) ) NEW_LINE distance ( root . left , target , tempsum , n ) NEW_LINE DEDENT if ( root . right ) : NEW_LINE INDENT tempsum = ( distancesum - root . right . size + ( n - root . right . size ) ) NEW_LINE distance ( root . right , target , tempsum , n ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT root = TreeNode ( 1 ) NEW_LINE root . left = TreeNode ( 2 ) NEW_LINE root . right = TreeNode ( 3 ) NEW_LINE root . left . left = TreeNode ( 4 ) NEW_LINE root . left . right = TreeNode ( 5 ) NEW_LINE root . right . left = TreeNode ( 6 ) NEW_LINE root . right . right = TreeNode ( 7 ) NEW_LINE root . left . left . left = TreeNode ( 8 ) NEW_LINE root . left . left . right = TreeNode ( 9 ) NEW_LINE target = 3 NEW_LINE p = sumofsubtree ( root ) NEW_LINE totalnodes = p [ 0 ] NEW_LINE distance ( root , target , p [ 1 ] , totalnodes ) NEW_LINE print ( sum ) NEW_LINE DEDENT
Rearrange array such that sum of same indexed elements is atmost K | ''Function to rearrange array such that sum of similar indexed elements does not exceed K ; '' Sort the array B[]  in descending order ; '' If condition fails ; '' Print the array ; ''Driver Code ; '' Given arrays
def rearrangeArray ( A , B , N , K ) : NEW_LINE INDENT B . sort ( reverse = True ) NEW_LINE flag = True NEW_LINE for i in range ( N ) : NEW_LINE INDENT if ( A [ i ] + B [ i ] > K ) : NEW_LINE INDENT flag = False NEW_LINE break NEW_LINE DEDENT DEDENT if ( flag == False ) : NEW_LINE INDENT print ( " - 1" ) NEW_LINE DEDENT else : NEW_LINE INDENT for i in range ( N ) : NEW_LINE INDENT print ( B [ i ] , end = " ▁ " ) NEW_LINE DEDENT DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT A = [ 1 , 2 , 3 , 4 , 2 ] NEW_LINE B = [ 1 , 2 , 3 , 1 , 1 ] NEW_LINE N = len ( A ) NEW_LINE K = 5 ; NEW_LINE rearrangeArray ( A , B , N , K ) NEW_LINE DEDENT
Count rows with sum exceeding sum of the remaining Matrix | ''Function to count the number of rows whose sum exceeds the sum of elements of the remaining matrix ; '' Stores the matrix dimensions ; '' To store the result ; '' Stores the total sum of  the matrix elements ; '' Calculate the total sum ; '' Traverse to check for each row ; '' Stores the sum of elements  of the current row ; '' Calculate the sum of elements  of the current row ; '' If sum of current row exceeds  the sum of rest of the matrix ; '' Increase count ; '' Print the result ; ''Driver Code ; '' Given matrix ; '' Function call
def countRows ( mat ) : NEW_LINE INDENT n = len ( mat ) NEW_LINE m = len ( mat [ 0 ] ) NEW_LINE count = 0 NEW_LINE totalSum = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT for j in range ( m ) : NEW_LINE INDENT totalSum += mat [ i ] [ j ] NEW_LINE DEDENT DEDENT for i in range ( n ) : NEW_LINE INDENT currSum = 0 NEW_LINE for j in range ( m ) : NEW_LINE INDENT currSum += mat [ i ] [ j ] NEW_LINE DEDENT if ( currSum > totalSum - currSum ) : NEW_LINE INDENT count += 1 NEW_LINE DEDENT DEDENT print ( count ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT mat = [ [ 2 , - 1 , 5 ] , [ - 3 , 0 , - 2 ] , [ 5 , 1 , 2 ] ] NEW_LINE countRows ( mat ) NEW_LINE DEDENT
Check if array contains contiguous integers with duplicates allowed | function to check whether the array contains a set of contiguous integers ; Sort the array ; After sorting , check if current element is either same as previous or is one more . ; Driver code
def areElementsContiguous ( arr , n ) : NEW_LINE INDENT arr . sort ( ) NEW_LINE for i in range ( 1 , n ) : NEW_LINE INDENT if ( arr [ i ] - arr [ i - 1 ] > 1 ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT DEDENT return 1 NEW_LINE DEDENT arr = [ 5 , 2 , 3 , 6 , 4 , 4 , 6 , 6 ] NEW_LINE n = len ( arr ) NEW_LINE if areElementsContiguous ( arr , n ) : print ( " Yes " ) NEW_LINE else : print ( " No " ) NEW_LINE
Check if array contains contiguous integers with duplicates allowed | function to check whether the array contains a set of contiguous integers ; Find maximum and minimum elements . ; There should be at least m elements in array to make them contiguous . ; Create a visited array and initialize fals ; Mark elements as true . ; If any element is not marked , all elements are not contiguous . ; Driver program
def areElementsContiguous ( arr , n ) : NEW_LINE INDENT max1 = max ( arr ) NEW_LINE min1 = min ( arr ) NEW_LINE m = max1 - min1 + 1 NEW_LINE if ( m > n ) : NEW_LINE INDENT return False NEW_LINE DEDENT visited = [ 0 ] * m NEW_LINE for i in range ( 0 , n ) : NEW_LINE INDENT visited [ arr [ i ] - min1 ] = True NEW_LINE DEDENT for i in range ( 0 , m ) : NEW_LINE INDENT if ( visited [ i ] == False ) : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT return True NEW_LINE DEDENT arr = [ 5 , 2 , 3 , 6 , 4 , 4 , 6 , 6 ] NEW_LINE n = len ( arr ) NEW_LINE if ( areElementsContiguous ( arr , n ) ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT
Check if array contains contiguous integers with duplicates allowed | Function to check whether the array contains a set of contiguous integers ; Storing elements of ' arr [ ] ' in a hash table 'us   ; As arr [ 0 ] is present in 'us   ; Starting with previous smaller element of arr [ 0 ] ; If ' curr _ ele ' is present in 'us   ; Increment count ; Update 'curr_ele" ; Starting with next greater element of arr [ 0 ] ; If ' curr _ ele ' is present in 'us   ; Increment count ; Update 'curr_ele" ; Returns true if array contains a set of contiguous integers else returns false ; Driver code
def areElementsContiguous ( arr ) : NEW_LINE INDENT us = set ( ) NEW_LINE for i in arr : us . add ( i ) NEW_LINE count = 1 NEW_LINE curr_ele = arr [ 0 ] - 1 NEW_LINE while curr_ele in us : NEW_LINE INDENT count += 1 NEW_LINE curr_ele -= 1 NEW_LINE DEDENT curr_ele = arr [ 0 ] + 1 NEW_LINE while curr_ele in us : NEW_LINE INDENT count += 1 NEW_LINE curr_ele += 1 NEW_LINE DEDENT return ( count == len ( us ) ) NEW_LINE DEDENT arr = [ 5 , 2 , 3 , 6 , 4 , 4 , 6 , 6 ] NEW_LINE if areElementsContiguous ( arr ) : print ( " Yes " ) NEW_LINE else : print ( " No " ) NEW_LINE
Longest subarray not having more than K distinct elements | function to print the longest sub - array ; mark the element visited ; if its visited first time , then increase the counter of distinct elements by 1 ; When the counter of distinct elements increases from k , then reduce it to k ; from the left , reduce the number of time of visit ; if the reduced visited time element is not present in further segment then decrease the count of distinct elements ; increase the subsegment mark ; check length of longest sub - segment when greater then previous best then change it ; print the longest sub - segment ; Driver Code
import collections NEW_LINE def longest ( a , n , k ) : NEW_LINE INDENT freq = collections . defaultdict ( int ) NEW_LINE start = 0 NEW_LINE end = 0 NEW_LINE now = 0 NEW_LINE l = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT freq [ a [ i ] ] += 1 NEW_LINE if ( freq [ a [ i ] ] == 1 ) : NEW_LINE INDENT now += 1 NEW_LINE DEDENT while ( now > k ) : NEW_LINE INDENT freq [ a [ l ] ] -= 1 NEW_LINE if ( freq [ a [ l ] ] == 0 ) : NEW_LINE INDENT now -= 1 NEW_LINE DEDENT l += 1 NEW_LINE DEDENT if ( i - l + 1 >= end - start + 1 ) : NEW_LINE INDENT end = i NEW_LINE start = l NEW_LINE DEDENT DEDENT for i in range ( start , end + 1 ) : NEW_LINE INDENT print ( a [ i ] , end = " ▁ " ) NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT a = [ 6 , 5 , 1 , 2 , 3 , 2 , 1 , 4 , 5 ] NEW_LINE n = len ( a ) NEW_LINE k = 3 NEW_LINE longest ( a , n , k ) NEW_LINE DEDENT
Check if any K ranges overlap at any point | Function that returns true if any k segments overlap at any point ; Vector to store the starting point and the ending point ; Starting points are marked by - 1 and ending points by + 1 ; Sort the vector by first element ; Stack to store the overlaps ; Get the current element ; If it is the starting point ; Push it in the stack ; It is the ending point ; Pop an element from stack ; If more than k ranges overlap ; Driver Code
def kOverlap ( pairs : list , k ) : NEW_LINE INDENT vec = list ( ) NEW_LINE for i in range ( len ( pairs ) ) : NEW_LINE INDENT vec . append ( ( pairs [ 0 ] , - 1 ) ) NEW_LINE vec . append ( ( pairs [ 1 ] , 1 ) ) NEW_LINE DEDENT vec . sort ( key = lambda a : a [ 0 ] ) NEW_LINE st = list ( ) NEW_LINE for i in range ( len ( vec ) ) : NEW_LINE INDENT cur = vec [ i ] NEW_LINE if cur [ 1 ] == - 1 : NEW_LINE INDENT st . append ( cur ) NEW_LINE DEDENT else : NEW_LINE INDENT st . pop ( ) NEW_LINE DEDENT if len ( st ) >= k : NEW_LINE INDENT return True NEW_LINE DEDENT DEDENT return False NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT pairs = list ( ) NEW_LINE pairs . append ( ( 1 , 3 ) ) NEW_LINE pairs . append ( ( 2 , 4 ) ) NEW_LINE pairs . append ( ( 3 , 5 ) ) NEW_LINE pairs . append ( ( 7 , 10 ) ) NEW_LINE n = len ( pairs ) NEW_LINE k = 3 NEW_LINE if kOverlap ( pairs , k ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT DEDENT
Find smallest range containing elements from k lists | Python3 program to finds out smallest range that includes elements from each of the given sorted lists . ; array for storing the current index of list i ; This function takes an k sorted lists in the form of 2D array as an argument . It finds out smallest range that includes elements from each of the k lists . ; initializing to 0 index ; for maintaining the index of list containing the minimum element ; iterating over all the list ; if every element of list [ i ] is traversed then break the loop ; find minimum value among all the list elements pointing by the ptr [ ] array ; update the index of the list ; find maximum value among all the list elements pointing by the ptr [ ] array ; if any list exhaust we will not get any better answer , so break the while loop ; updating the minrange ; Driver code
N = 5 NEW_LINE ptr = [ 0 for i in range ( 501 ) ] NEW_LINE def findSmallestRange ( arr , n , k ) : NEW_LINE INDENT i , minval , maxval , minrange , minel , maxel , flag , minind = 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 NEW_LINE for i in range ( k + 1 ) : NEW_LINE INDENT ptr [ i ] = 0 NEW_LINE DEDENT minrange = 10 ** 9 NEW_LINE while ( 1 ) : NEW_LINE INDENT minind = - 1 NEW_LINE minval = 10 ** 9 NEW_LINE maxval = - 10 ** 9 NEW_LINE flag = 0 NEW_LINE for i in range ( k ) : NEW_LINE INDENT if ( ptr [ i ] == n ) : NEW_LINE INDENT flag = 1 NEW_LINE break NEW_LINE DEDENT if ( ptr [ i ] < n and arr [ i ] [ ptr [ i ] ] < minval ) : NEW_LINE INDENT minind = i NEW_LINE minval = arr [ i ] [ ptr [ i ] ] NEW_LINE DEDENT if ( ptr [ i ] < n and arr [ i ] [ ptr [ i ] ] > maxval ) : NEW_LINE INDENT maxval = arr [ i ] [ ptr [ i ] ] NEW_LINE DEDENT DEDENT if ( flag ) : NEW_LINE INDENT break NEW_LINE DEDENT ptr [ minind ] += 1 NEW_LINE if ( ( maxval - minval ) < minrange ) : NEW_LINE INDENT minel = minval NEW_LINE maxel = maxval NEW_LINE minrange = maxel - minel NEW_LINE DEDENT DEDENT print ( " The ▁ smallest ▁ range ▁ is ▁ [ " , minel , maxel , " ] " ) NEW_LINE DEDENT arr = [ [ 4 , 7 , 9 , 12 , 15 ] , [ 0 , 8 , 10 , 14 , 20 ] , [ 6 , 12 , 16 , 30 , 50 ] ] NEW_LINE k = len ( arr ) NEW_LINE findSmallestRange ( arr , N , k ) NEW_LINE
Find largest d in array such that a + b + c = d | function to find largest d ; sort the array in ascending order ; iterating from backwards to find the required largest d ; since all four a , b , c , d should be distinct ; if the current combination of j , k , l in the set is equal to S [ i ] return this value as this would be the largest d since we are iterating in descending order ; Driver Code
def findLargestd ( S , n ) : NEW_LINE INDENT found = False NEW_LINE S . sort ( ) NEW_LINE for i in range ( n - 1 , - 1 , - 1 ) : NEW_LINE INDENT for j in range ( 0 , n ) : NEW_LINE INDENT if ( i == j ) : NEW_LINE INDENT continue NEW_LINE DEDENT for k in range ( j + 1 , n ) : NEW_LINE INDENT if ( i == k ) : NEW_LINE INDENT continue NEW_LINE DEDENT for l in range ( k + 1 , n ) : NEW_LINE INDENT if ( i == l ) : NEW_LINE INDENT continue NEW_LINE DEDENT if ( S [ i ] == S [ j ] + S [ k ] + S [ l ] ) : NEW_LINE INDENT found = True NEW_LINE return S [ i ] NEW_LINE DEDENT DEDENT DEDENT DEDENT DEDENT if ( found == False ) : NEW_LINE INDENT return - 1 NEW_LINE DEDENT DEDENT S = [ 2 , 3 , 5 , 7 , 12 ] NEW_LINE n = len ( S ) NEW_LINE ans = findLargestd ( S , n ) NEW_LINE if ( ans == - 1 ) : NEW_LINE INDENT print ( " No ▁ Solution " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " Largest ▁ d ▁ such ▁ that ▁ a ▁ + ▁ b ▁ + " , " c ▁ = ▁ d ▁ is " , ans ) NEW_LINE DEDENT
Find largest d in array such that a + b + c = d | The function finds four elements with given sum X ; Store sums ( a + b ) of all pairs ( a , b ) in a hash table ; Traverse through all pairs and find ( d - c ) is present in hash table ; If d - c is present in hash table , ; Making sure that all elements are distinct array elements and an element is not considered more than once . ; Driver Code
def findFourElements ( arr , n ) : NEW_LINE INDENT mp = dict ( ) NEW_LINE for i in range ( n - 1 ) : NEW_LINE INDENT for j in range ( i + 1 , n ) : NEW_LINE INDENT mp [ arr [ i ] + arr [ j ] ] = ( i , j ) NEW_LINE DEDENT DEDENT d = - 10 ** 9 NEW_LINE for i in range ( n - 1 ) : NEW_LINE INDENT for j in range ( i + 1 , n ) : NEW_LINE INDENT abs_diff = abs ( arr [ i ] - arr [ j ] ) NEW_LINE if abs_diff in mp . keys ( ) : NEW_LINE INDENT p = mp [ abs_diff ] NEW_LINE if ( p [ 0 ] != i and p [ 0 ] != j and p [ 1 ] != i and p [ 1 ] != j ) : NEW_LINE INDENT d = max ( d , max ( arr [ i ] , arr [ j ] ) ) NEW_LINE DEDENT DEDENT DEDENT DEDENT return d NEW_LINE DEDENT arr = [ 2 , 3 , 5 , 7 , 12 ] NEW_LINE n = len ( arr ) NEW_LINE res = findFourElements ( arr , n ) NEW_LINE if ( res == - 10 ** 9 ) : NEW_LINE INDENT print ( " No ▁ Solution . " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( res ) NEW_LINE DEDENT