codeparrot/xlcost-text-to-code huggingface dataset:
Check if two elements of a matrix are on the same diagonal or not | Function to check if two integers are on the same diagonal of the matrix ; Storing Indexes of y in P , Q ; Condition to check if the both the elements are in same diagonal of a matrix ; Driver Code ; Dimensions of Matrix ; Given Matrix ; elements to be checked ; Function Call
def checkSameDiag ( x , y ) : NEW_LINE INDENT for i in range ( m ) : NEW_LINE INDENT for j in range ( n ) : NEW_LINE INDENT if li [ i ] [ j ] == x : NEW_LINE INDENT I , J = i , j NEW_LINE DEDENT if li [ i ] [ j ] == y : NEW_LINE INDENT P , Q = i , j NEW_LINE DEDENT DEDENT DEDENT if P - Q == I - J or P + Q == I + J : NEW_LINE INDENT print ( " YES " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " NO " ) NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT m , n = 6 , 5 NEW_LINE li = [ [ 32 , 94 , 99 , 26 , 82 ] , [ 51 , 69 , 52 , 63 , 17 ] , [ 90 , 36 , 88 , 55 , 33 ] , [ 93 , 42 , 73 , 39 , 28 ] , [ 81 , 31 , 83 , 53 , 10 ] , [ 12 , 29 , 85 , 80 , 87 ] ] NEW_LINE x , y = 42 , 80 NEW_LINE checkSameDiag ( x , y ) NEW_LINE DEDENT
Count of decrement operations required to obtain K in N steps | Function to check whether m number of steps of type 1 are valid or not ; If m and n are the count of operations of type 1 and type 2 respectively , then n - m operations are performed ; Find the value of S after step 2 ; If m steps of type 1 is valid ; Function to find the number of operations of type 1 required ; Iterate over the range ; Find the value of mid ; Check if m steps of type 1 are valid or not ; If mid is the valid number of steps ; If no valid number of steps exist ; Given and N , K ; Function call
def isValid ( n , m , k ) : NEW_LINE INDENT step2 = n - m NEW_LINE cnt = ( step2 * ( step2 + 1 ) ) // 2 NEW_LINE if ( cnt - m == k ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT if ( cnt - m > k ) : NEW_LINE INDENT return 1 NEW_LINE DEDENT return - 1 NEW_LINE DEDENT def countOfOperations ( n , k ) : NEW_LINE INDENT start = 0 NEW_LINE end = n NEW_LINE ok = 1 NEW_LINE while ( start <= end ) : NEW_LINE INDENT mid = ( start + end ) // 2 NEW_LINE temp = isValid ( n , mid , k ) NEW_LINE if ( temp == 0 ) : NEW_LINE INDENT ok = 0 NEW_LINE print ( mid ) NEW_LINE break NEW_LINE DEDENT elif ( temp == 1 ) : NEW_LINE INDENT start = mid + 1 NEW_LINE DEDENT else : NEW_LINE INDENT end = mid - 1 NEW_LINE DEDENT DEDENT if ( ok ) : NEW_LINE INDENT print ( " - 1" ) NEW_LINE DEDENT DEDENT N = 5 NEW_LINE K = 4 NEW_LINE countOfOperations ( N , K ) NEW_LINE
Print all Possible Decodings of a given Digit Sequence | Function to check if all the characters are lowercase or not ; Traverse the string ; If any character is not found to be in lowerCase ; Function to print the decodings ; If all characters are not in lowercase ; Function to return the character corresponding to given integer ; Function to return the decodings ; Base case ; Recursive call ; Stores the characters of two digit numbers ; Extract first digit and first two digits ; Check if it lies in the range of alphabets ; Next recursive call ; Combine both the output in a single readonly output array ; Index of readonly output array ; Store the elements of output1 in readonly output array ; Store the elements of output2 in readonly output array ; Result the result ; Driver Code ; Function call ; Print function call
def nonLower ( s ) : NEW_LINE INDENT for i in range ( len ( s ) ) : NEW_LINE INDENT if not s [ i ] . islower ( ) : NEW_LINE INDENT return True NEW_LINE DEDENT DEDENT return False NEW_LINE DEDENT def printCodes ( output ) : NEW_LINE INDENT for i in range ( len ( output ) ) : NEW_LINE INDENT if ( nonLower ( output [ i ] ) ) : NEW_LINE INDENT continue NEW_LINE DEDENT print ( output [ i ] ) NEW_LINE DEDENT DEDENT def getChar ( n ) : NEW_LINE INDENT return chr ( n + 96 ) NEW_LINE DEDENT def getCode ( str ) : NEW_LINE INDENT if ( len ( str ) == 0 ) : NEW_LINE INDENT ans = [ " " ] NEW_LINE return ans NEW_LINE DEDENT output1 = getCode ( str [ 1 : ] ) NEW_LINE output2 = [ ] NEW_LINE firstDigit = ( ord ( str [ 0 ] ) - ord ( '0' ) ) NEW_LINE firstTwoDigit = 0 NEW_LINE if ( len ( str ) >= 2 ) : NEW_LINE firstTwoDigit = ( ( ord ( str [ 0 ] ) - ord ( '0' ) ) * 10 + ( ord ( str [ 1 ] ) - ord ( '0' ) ) ) NEW_LINE if ( firstTwoDigit >= 10 and firstTwoDigit <= 26 ) : NEW_LINE INDENT output2 = getCode ( str [ 2 : ] ) NEW_LINE DEDENT output = [ ' ' for i in range ( len ( output1 ) + len ( output2 ) ) ] NEW_LINE k = 0 NEW_LINE for i in range ( len ( output1 ) ) : NEW_LINE INDENT ch = getChar ( firstDigit ) NEW_LINE output [ i ] = ch + output1 [ i ] NEW_LINE k += 1 NEW_LINE DEDENT for i in range ( len ( output2 ) ) : NEW_LINE INDENT ch = getChar ( firstTwoDigit ) NEW_LINE output [ k ] = ch + output2 [ i ] NEW_LINE k += 1 NEW_LINE DEDENT return output NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT input = "101" NEW_LINE output = getCode ( input ) NEW_LINE printCodes ( output ) NEW_LINE DEDENT
Count prime numbers that can be expressed as sum of consecutive prime numbers | Function to check if a number is prime or not ; Base Case ; Iterate till [ 5 , sqrt ( N ) ] to detect primality of numbers ; If N is divisible by i or i + 2 ; Return 1 if N is prime ; Function to count the prime numbers which can be expressed as sum of consecutive prime numbers ; Initialize count as 0 ; Stores prime numbers ; If i is prime ; Initialize the sum ; Find all required primes upto N ; Add it to the sum ; Return the final count ; Given number N ; Function call
def isprm ( n ) : NEW_LINE INDENT if ( n <= 1 ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT if ( n <= 3 ) : NEW_LINE INDENT return 1 NEW_LINE DEDENT if ( n % 2 == 0 or n % 3 == 0 ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT i = 5 NEW_LINE while ( i * i <= n ) : NEW_LINE INDENT if ( n % i == 0 or n % ( i + 2 ) == 0 ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT i = i + 6 NEW_LINE DEDENT return 1 NEW_LINE DEDENT def countprime ( n ) : NEW_LINE INDENT count = 0 NEW_LINE primevector = [ ] NEW_LINE for i in range ( 2 , n + 1 ) : NEW_LINE INDENT if ( isprm ( i ) == 1 ) : NEW_LINE INDENT primevector . append ( i ) NEW_LINE DEDENT DEDENT sum = primevector [ 0 ] NEW_LINE for i in range ( 1 , len ( primevector ) ) : NEW_LINE INDENT sum += primevector [ i ] NEW_LINE if ( sum > n ) : NEW_LINE INDENT break NEW_LINE DEDENT if ( isprm ( sum ) == 1 ) : NEW_LINE INDENT count += 1 NEW_LINE DEDENT DEDENT return count NEW_LINE DEDENT N = 45 NEW_LINE print ( countprime ( N ) ) NEW_LINE
Find a subarray of size K whose sum is a perfect square | Python3 program for the above approach ; Function to check if a given number is a perfect square or not ; Find square root of n ; Check if the square root is an integer or not ; Function to print the subarray whose sum is a perfect square ; Sum of first K elements ; If the first k elements have a sum as perfect square ; Iterate through the array ; If sum is perfect square ; If subarray not found ; Driver Code ; Given array ; Given subarray size K ; Function call
from math import sqrt , ceil , floor NEW_LINE def isPerfectSquare ( n ) : NEW_LINE INDENT sr = sqrt ( n ) NEW_LINE return ( ( sr - floor ( sr ) ) == 0 ) NEW_LINE DEDENT def SubarrayHavingPerfectSquare ( arr , k ) : NEW_LINE INDENT ans = [ 0 , 0 ] NEW_LINE sum = 0 NEW_LINE i = 0 NEW_LINE while i < k : NEW_LINE INDENT sum += arr [ i ] NEW_LINE i += 1 NEW_LINE DEDENT found = False NEW_LINE if ( isPerfectSquare ( sum ) ) : NEW_LINE INDENT ans [ 0 ] = 0 NEW_LINE ans [ 1 ] = i - 1 NEW_LINE DEDENT else : NEW_LINE INDENT for j in range ( i , len ( arr ) ) : NEW_LINE INDENT sum = sum + arr [ j ] - arr [ j - k ] NEW_LINE if ( isPerfectSquare ( sum ) ) : NEW_LINE INDENT found = True NEW_LINE ans [ 0 ] = j - k + 1 NEW_LINE ans [ 1 ] = j NEW_LINE DEDENT DEDENT for k in range ( ans [ 0 ] , ans [ 1 ] + 1 ) : NEW_LINE INDENT print ( arr [ k ] , end = " ▁ " ) NEW_LINE DEDENT DEDENT if ( found == False ) : NEW_LINE INDENT print ( " - 1" ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 20 , 34 , 51 , 10 , 99 , 87 , 23 , 45 ] NEW_LINE K = 3 NEW_LINE SubarrayHavingPerfectSquare ( arr , K ) NEW_LINE DEDENT
Check if any permutation of a number without any leading zeros is a power of 2 or not | Python3 program for the above approach ; Function to update the frequency array such that freq [ i ] stores the frequency of digit i to n ; While there are digits left to process ; Update the frequency of the current digit ; Remove the last digit ; Function that returns true if a and b are anagrams of each other ; To store the frequencies of the digits in a and b ; Update the frequency of the digits in a ; Update the frequency of the digits in b ; Match the frequencies of the common digits ; If frequency differs for any digit then the numbers are not anagrams of each other ; Function to check if any permutation of a number is a power of 2 or not ; Iterate over all possible perfect power of 2 ; Print that number ; Given number N ; Function call
TEN = 10 NEW_LINE def updateFreq ( n , freq ) : NEW_LINE INDENT while ( n ) : NEW_LINE INDENT digit = n % TEN NEW_LINE freq [ digit ] += 1 NEW_LINE n //= TEN NEW_LINE DEDENT DEDENT def areAnagrams ( a , b ) : NEW_LINE INDENT freqA = [ 0 ] * ( TEN ) NEW_LINE freqB = [ 0 ] * ( TEN ) NEW_LINE updateFreq ( a , freqA ) NEW_LINE updateFreq ( b , freqB ) NEW_LINE for i in range ( TEN ) : NEW_LINE INDENT if ( freqA [ i ] != freqB [ i ] ) : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT return True NEW_LINE DEDENT def isPowerOf2 ( N ) : NEW_LINE INDENT for i in range ( 32 ) : NEW_LINE INDENT if ( areAnagrams ( 1 << i , N ) ) : NEW_LINE INDENT print ( 1 << i ) NEW_LINE return True NEW_LINE DEDENT DEDENT return False NEW_LINE DEDENT N = 46 NEW_LINE if ( isPowerOf2 ( N ) == 0 ) : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT
Count number of triangles possible with length of sides not exceeding N | Function to count total number of right angled triangle ; Initialise count with 0 ; Run three nested loops and check all combinations of sides ; Condition for right angled triangle ; Increment count ; Given N ; Function call
def right_angled ( n ) : NEW_LINE INDENT count = 0 NEW_LINE for z in range ( 1 , n + 1 ) : NEW_LINE INDENT for y in range ( 1 , z + 1 ) : NEW_LINE INDENT for x in range ( 1 , y + 1 ) : NEW_LINE INDENT if ( ( x * x ) + ( y * y ) == ( z * z ) ) : NEW_LINE INDENT count += 1 NEW_LINE DEDENT DEDENT DEDENT DEDENT return count NEW_LINE DEDENT n = 5 NEW_LINE print ( right_angled ( n ) ) NEW_LINE
Check if the given two matrices are mirror images of one another | Function to check whether the two matrices are mirror of each other ; Initialising row and column of second matrix ; Iterating over the matrices ; Check row of first matrix with reversed row of second matrix ; If the element is not equal ; Increment column ; Reset column to 0 for new row ; Increment row ; Driver code ; Given 2 matrices ; Function call
def mirrorMatrix ( mat1 , mat2 , N ) : NEW_LINE INDENT row = 0 NEW_LINE col = 0 NEW_LINE isMirrorImage = True NEW_LINE for i in range ( N ) : NEW_LINE INDENT for j in range ( N - 1 , - 1 , - 1 ) : NEW_LINE INDENT if ( mat2 [ row ] [ col ] != mat1 [ i ] [ j ] ) : NEW_LINE INDENT isMirrorImage = False NEW_LINE DEDENT col += 1 NEW_LINE DEDENT col = 0 NEW_LINE row += 1 NEW_LINE DEDENT if ( isMirrorImage ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 4 NEW_LINE mat1 = [ [ 1 , 2 , 3 , 4 ] , [ 0 , 6 , 7 , 8 ] , [ 9 , 10 , 11 , 12 ] , [ 13 , 14 , 15 , 16 ] ] NEW_LINE mat2 = [ [ 4 , 3 , 2 , 1 ] , [ 8 , 7 , 6 , 0 ] , [ 12 , 11 , 10 , 9 ] , [ 16 , 15 , 14 , 13 ] ] NEW_LINE mirrorMatrix ( mat1 , mat2 , N ) NEW_LINE DEDENT
Calculate number of nodes between two vertices in an acyclic Graph by DFS method | Function to return the count of nodes in the path from source to destination ; Mark the node visited ; If dest is reached ; Traverse all adjacent nodes ; If not already visited ; If there is path , then include the current node ; Return 0 if there is no path between src and dest through the current node ; Function to return the count of nodes between two given vertices of the acyclic Graph ; Initialize an adjacency list ; Populate the edges in the list ; Mark all the nodes as not visited ; Count nodes in the path from src to dest ; Return the nodes between src and dest ; Driver Code ; Given number of vertices and edges ; Given source and destination vertices ; Given edges
def dfs ( src , dest , vis , adj ) : NEW_LINE INDENT vis [ src ] = 1 NEW_LINE if ( src == dest ) : NEW_LINE INDENT return 1 NEW_LINE DEDENT for u in adj [ src ] : NEW_LINE INDENT if not vis [ u ] : NEW_LINE INDENT temp = dfs ( u , dest , vis , adj ) NEW_LINE if ( temp != 0 ) : NEW_LINE INDENT return temp + 1 NEW_LINE DEDENT DEDENT DEDENT return 0 NEW_LINE DEDENT def countNodes ( V , E , src , dest , edges ) : NEW_LINE INDENT adj = [ [ ] for i in range ( V + 1 ) ] NEW_LINE for i in range ( E ) : NEW_LINE INDENT adj [ edges [ i ] [ 0 ] ] . append ( edges [ i ] [ 1 ] ) NEW_LINE adj [ edges [ i ] [ 1 ] ] . append ( edges [ i ] [ 0 ] ) NEW_LINE DEDENT vis = [ 0 ] * ( V + 1 ) NEW_LINE count = dfs ( src , dest , vis , adj ) NEW_LINE return count - 2 NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT V = 8 NEW_LINE E = 7 NEW_LINE src = 5 NEW_LINE dest = 2 NEW_LINE edges = [ [ 1 , 4 ] , [ 4 , 5 ] , [ 4 , 2 ] , [ 2 , 6 ] , [ 6 , 3 ] , [ 2 , 7 ] , [ 3 , 8 ] ] NEW_LINE print ( countNodes ( V , E , src , dest , edges ) ) NEW_LINE DEDENT
Check if all array elements are pairwise co | Function to calculate GCD ; Function to calculate LCM ; Function to check if aelements in the array are pairwise coprime ; Initialize variables ; Iterate over the array ; Calculate product of array elements ; Calculate LCM of array elements ; If the product of array elements is equal to LCM of the array ; Driver Code ; Function call
def GCD ( a , b ) : NEW_LINE INDENT if ( a == 0 ) : NEW_LINE INDENT return b NEW_LINE DEDENT return GCD ( b % a , a ) NEW_LINE DEDENT def LCM ( a , b ) : NEW_LINE INDENT return ( a * b ) // GCD ( a , b ) NEW_LINE DEDENT def checkPairwiseCoPrime ( A , n ) : NEW_LINE INDENT prod = 1 NEW_LINE lcm = 1 NEW_LINE for i in range ( n ) : NEW_LINE INDENT prod *= A [ i ] NEW_LINE lcm = LCM ( A [ i ] , lcm ) NEW_LINE DEDENT if ( prod == lcm ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT A = [ 2 , 3 , 5 ] NEW_LINE n = len ( A ) NEW_LINE checkPairwiseCoPrime ( A , n ) NEW_LINE DEDENT
Partition a set into two non | Python3 program for above approach ; Function to return the maximum difference between the subset sums ; Stores the total sum of the array ; Checks for positive and negative elements ; Stores the minimum element from the given array ; Traverse the array ; Calculate total sum ; Mark positive element present in the set ; Mark negative element present in the set ; Find the minimum element of the set ; If the array contains both positive and negative elements ; Otherwise ; Driver Code ; Given the array ; Length of the array ; Function Call
import sys NEW_LINE def maxDiffSubsets ( arr ) : NEW_LINE INDENT totalSum = 0 NEW_LINE pos = False NEW_LINE neg = False NEW_LINE min = sys . maxsize NEW_LINE for i in range ( len ( arr ) ) : NEW_LINE INDENT totalSum += abs ( arr [ i ] ) NEW_LINE if ( arr [ i ] > 0 ) : NEW_LINE INDENT pos = True NEW_LINE DEDENT if ( arr [ i ] < 0 ) : NEW_LINE INDENT neg = True NEW_LINE DEDENT if ( arr [ i ] < min ) : NEW_LINE INDENT min = arr [ i ] NEW_LINE DEDENT DEDENT if ( pos and neg ) : NEW_LINE INDENT return totalSum NEW_LINE DEDENT else : NEW_LINE INDENT return totalSum - 2 * min NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT S = [ 1 , 2 , 1 ] NEW_LINE N = len ( S ) NEW_LINE if ( N < 2 ) : NEW_LINE INDENT print ( " Not ▁ Possible " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( maxDiffSubsets ( S ) ) NEW_LINE DEDENT DEDENT
Split array into two subarrays such that difference of their sum is minimum | Python3 program for the above approach ; Function to return minimum difference between two subarray sums ; To store prefix sums ; Generate prefix sum array ; To store suffix sums ; Generate suffix sum array ; Stores the minimum difference ; Traverse the given array ; Calculate the difference ; Update minDiff ; Return minDiff ; Driver Code ; Given array ; Length of the array
import sys NEW_LINE def minDiffSubArray ( arr , n ) : NEW_LINE INDENT prefix_sum = [ 0 ] * n NEW_LINE prefix_sum [ 0 ] = arr [ 0 ] NEW_LINE for i in range ( 1 , n ) : NEW_LINE INDENT prefix_sum [ i ] = ( prefix_sum [ i - 1 ] + arr [ i ] ) NEW_LINE DEDENT suffix_sum = [ 0 ] * n NEW_LINE suffix_sum [ n - 1 ] = arr [ n - 1 ] NEW_LINE for i in range ( n - 2 , - 1 , - 1 ) : NEW_LINE INDENT suffix_sum [ i ] = ( suffix_sum [ i + 1 ] + arr [ i ] ) NEW_LINE DEDENT minDiff = sys . maxsize NEW_LINE for i in range ( n - 1 ) : NEW_LINE INDENT diff = abs ( prefix_sum [ i ] - suffix_sum [ i + 1 ] ) NEW_LINE if ( diff < minDiff ) : NEW_LINE INDENT minDiff = diff NEW_LINE DEDENT DEDENT return minDiff NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 7 , 9 , 5 , 10 ] NEW_LINE n = len ( arr ) NEW_LINE print ( minDiffSubArray ( arr , n ) ) NEW_LINE DEDENT
Count of days remaining for the next day with higher temperature | Function to determine how many days required to wait for the next warmer temperature ; To store the answer ; Traverse all the temperatures ; Check if current index is the next warmer temperature of any previous indexes ; Pop the element ; Push the current index ; Print waiting days ; Given temperatures ; Function call
def dailyTemperatures ( T ) : NEW_LINE INDENT n = len ( T ) NEW_LINE daysOfWait = [ - 1 ] * n NEW_LINE s = [ ] NEW_LINE for i in range ( n ) : NEW_LINE INDENT while ( len ( s ) != 0 and T [ s [ - 1 ] ] < T [ i ] ) : NEW_LINE INDENT daysOfWait [ s [ - 1 ] ] = i - s [ - 1 ] NEW_LINE s . pop ( - 1 ) NEW_LINE DEDENT s . append ( i ) NEW_LINE DEDENT for i in range ( n ) : NEW_LINE INDENT print ( daysOfWait [ i ] , end = " ▁ " ) NEW_LINE DEDENT DEDENT arr = [ 73 , 74 , 75 , 71 , 69 , 72 , 76 , 73 ] NEW_LINE dailyTemperatures ( arr ) NEW_LINE
Check if an array contains only one distinct element | Function to find if the array contains only one distinct element ; Create a set ; Compare and print the result ; Driver code ; Function call
def uniqueElement ( arr , n ) : NEW_LINE INDENT s = set ( arr ) NEW_LINE if ( len ( s ) == 1 ) : NEW_LINE INDENT print ( ' YES ' ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( ' NO ' ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 9 , 9 , 9 , 9 , 9 , 9 , 9 ] NEW_LINE n = len ( arr ) NEW_LINE uniqueElement ( arr , n ) NEW_LINE DEDENT
Maximum cost of splitting given Binary Tree into two halves | To store the results and sum of all nodes in the array ; To create adjacency list ; Function to add edges into the adjacency list ; Recursive function that calculate the value of the cost of splitting the tree recursively ; Fetch the child of node - r ; Neglect if cur node is parent ; Add all values of nodes which are decendents of r ; The two trees formed are rooted at ' r ' with its decendents ; Check and replace if current product t1 * t2 is large ; Function to find the maximum cost after splitting the tree in 2 halves ; Find sum of values in all nodes ; Traverse edges to create adjacency list ; Function Call ; Driver Code ; Values in each node ; Given Edges
ans = 0 NEW_LINE allsum = 0 NEW_LINE edges = [ [ ] for i in range ( 100001 ) ] NEW_LINE def addedge ( a , b ) : NEW_LINE INDENT global edges NEW_LINE edges [ a ] . append ( b ) NEW_LINE edges [ b ] . append ( a ) NEW_LINE DEDENT def findCost ( r , p , arr ) : NEW_LINE INDENT global edges NEW_LINE global ans NEW_LINE global allsum NEW_LINE i = 0 NEW_LINE for i in range ( len ( edges [ r ] ) ) : NEW_LINE INDENT cur = edges [ r ] [ i ] NEW_LINE if ( cur == p ) : NEW_LINE INDENT continue NEW_LINE DEDENT findCost ( cur , r , arr ) NEW_LINE arr [ r ] += arr [ cur ] NEW_LINE DEDENT t1 = arr [ r ] NEW_LINE t2 = allsum - t1 NEW_LINE if ( t1 * t2 > ans ) : NEW_LINE INDENT ans = t1 * t2 NEW_LINE DEDENT DEDENT def maximumCost ( r , p , N , M , arr , Edges ) : NEW_LINE INDENT global allsum NEW_LINE for i in range ( N ) : NEW_LINE INDENT allsum += arr [ i ] NEW_LINE DEDENT for i in range ( M ) : NEW_LINE INDENT addedge ( Edges [ i ] [ 0 ] , Edges [ i ] [ 1 ] ) NEW_LINE DEDENT findCost ( r , p , arr ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 6 NEW_LINE arr = [ 13 , 8 , 7 , 4 , 5 , 9 ] NEW_LINE M = 5 NEW_LINE Edges = [ [ 0 , 1 ] , [ 1 , 2 ] , [ 1 , 4 ] , [ 3 , 4 ] , [ 4 , 5 ] ] NEW_LINE maximumCost ( 1 , - 1 , N , M , arr , Edges ) NEW_LINE print ( ans ) NEW_LINE DEDENT
Diameters for each node of Tree after connecting it with given disconnected component | Python3 program to implement the above approach ; Keeps track of the farthest end of the diameter ; Keeps track of the length of the diameter ; Stores the nodes which are at ends of the diameter ; Perform DFS on the given tree ; Update diameter and X ; If current node is an end of diameter ; Traverse its neighbors ; Function to call DFS for the required purposes ; DFS from a random node and find the node farthest from it ; DFS from X to calculate diameter ; DFS from farthest_node to find the farthest node ( s ) from it ; DFS from X ( other end of diameter ) and check the farthest node ( s ) from it ; If node i is the end of a diameter ; Increase diameter by 1 ; Otherwise ; Remains unchanged ; constructed tree is 1 / \ 2 3 / | \ 4 5 6 | 7 ; Creating undirected edges
from collections import defaultdict NEW_LINE X = 1 NEW_LINE diameter = 0 NEW_LINE mp = defaultdict ( lambda : 0 ) NEW_LINE def dfs ( current_node , prev_node , len , add_to_map , adj ) : NEW_LINE INDENT global diameter , X NEW_LINE if len > diameter : NEW_LINE INDENT diameter = len NEW_LINE X = current_node NEW_LINE DEDENT if add_to_map and len == diameter : NEW_LINE INDENT mp [ current_node ] = 1 NEW_LINE DEDENT for it in adj [ current_node ] : NEW_LINE INDENT if it != prev_node : NEW_LINE INDENT dfs ( it , current_node , len + 1 , add_to_map , adj ) NEW_LINE DEDENT DEDENT DEDENT def dfsUtility ( adj ) : NEW_LINE INDENT dfs ( 1 , - 1 , 0 , 0 , adj ) NEW_LINE farthest_node = X NEW_LINE dfs ( farthest_node , - 1 , 0 , 0 , adj ) NEW_LINE dfs ( farthest_node , - 1 , 0 , 1 , adj ) NEW_LINE dfs ( X , - 1 , 0 , 1 , adj ) NEW_LINE DEDENT def printDiameters ( adj ) : NEW_LINE INDENT global diameter NEW_LINE dfsUtility ( adj ) NEW_LINE for i in range ( 1 , 6 + 1 ) : NEW_LINE INDENT if mp [ i ] == 1 : NEW_LINE INDENT print ( diameter + 1 , end = " , ▁ " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( diameter , end = " , ▁ " ) NEW_LINE DEDENT DEDENT DEDENT adj = [ ] NEW_LINE for i in range ( 7 ) : NEW_LINE INDENT adj . append ( [ ] ) NEW_LINE DEDENT adj [ 1 ] . append ( 2 ) NEW_LINE adj [ 2 ] . append ( 1 ) NEW_LINE adj [ 1 ] . append ( 3 ) NEW_LINE adj [ 3 ] . append ( 1 ) NEW_LINE adj [ 2 ] . append ( 4 ) NEW_LINE adj [ 4 ] . append ( 2 ) NEW_LINE adj [ 2 ] . append ( 5 ) NEW_LINE adj [ 5 ] . append ( 2 ) NEW_LINE adj [ 2 ] . append ( 6 ) NEW_LINE adj [ 6 ] . append ( 2 ) NEW_LINE printDiameters ( adj ) NEW_LINE