text
stringlengths 17
3.65k
| code
stringlengths 70
5.84k
|
---|---|
Find if a point lies inside , outside or on the circumcircle of three points A , B , C | Function to find the line given two points ; Function which converts the input line to its perpendicular bisector . It also inputs the points whose mid - lies o on the bisector ; Find the mid point ; x coordinates ; y coordinates ; c = - bx + ay ; Assign the coefficient of a and b ; Returns the intersection of two lines ; Find determinant ; Returns the intersection of two lines ; Find determinant ; Function to find the point lies inside , outside or on the circle ; Store the coordinates radius of circumcircle ; Line PQ is represented as ax + by = c ; Line QR is represented as ex + fy = g ; Converting lines PQ and QR to perpendicular bisectors . After this , L = ax + by = c M = ex + fy = g ; The of intersection of L and M gives r as the circumcenter ; Length of radius ; Distance between radius and the given D ; Condition for lies inside circumcircle ; Condition for lies on circumcircle ; Condition for lies outside circumcircle ; Driver Code ; Given Points ; Function call to find the lies inside , outside or on the circle | def lineFromPoints ( P , Q , a , b , c ) : NEW_LINE INDENT a = Q [ 1 ] - P [ 1 ] NEW_LINE b = P [ 0 ] - Q [ 0 ] NEW_LINE c = a * ( P [ 0 ] ) + b * ( P [ 1 ] ) NEW_LINE return a , b , c NEW_LINE DEDENT def perpenBisectorFromLine ( P , Q , a , b , c ) : NEW_LINE INDENT mid_point = [ 0 , 0 ] NEW_LINE mid_point [ 0 ] = ( P [ 0 ] + Q [ 0 ] ) / 2 NEW_LINE mid_point [ 1 ] = ( P [ 1 ] + Q [ 1 ] ) / 2 NEW_LINE c = ( - b * ( mid_point [ 0 ] ) + a * ( mid_point [ 1 ] ) ) NEW_LINE temp = a NEW_LINE a = - b NEW_LINE b = temp NEW_LINE return a , b , c NEW_LINE DEDENT def LineInterX ( a1 , b1 , c1 , a2 , b2 , c2 ) : NEW_LINE INDENT determ = a1 * b2 - a2 * b1 NEW_LINE x = ( b2 * c1 - b1 * c2 ) NEW_LINE x /= determ NEW_LINE return x NEW_LINE DEDENT def LineInterY ( a1 , b1 , c1 , a2 , b2 , c2 ) : NEW_LINE INDENT determ = a1 * b2 - a2 * b1 NEW_LINE y = ( a1 * c2 - a2 * c1 ) NEW_LINE print ( y ) NEW_LINE y /= determ NEW_LINE return y NEW_LINE DEDENT def findPosition ( P , Q , R , D ) : NEW_LINE INDENT r = [ 0 , 0 ] NEW_LINE a , b , c = lineFromPoints ( P , Q , 0 , 0 , 0 ) NEW_LINE e , f , g = lineFromPoints ( Q , R , 0 , 0 , 0 ) NEW_LINE a , b , c = perpenBisectorFromLine ( P , Q , a , b , c ) NEW_LINE e , f , g = perpenBisectorFromLine ( Q , R , e , f , g ) NEW_LINE r [ 0 ] = LineInterX ( a , b , c , e , f , g ) NEW_LINE r [ 1 ] = LineInterY ( a , b , c , e , f , g ) NEW_LINE q = ( ( r [ 0 ] - P [ 0 ] ) * ( r [ 0 ] - P [ 0 ] ) + ( r [ 1 ] - P [ 1 ] ) * ( r [ 1 ] - P [ 1 ] ) ) NEW_LINE dis = ( ( r [ 0 ] - D [ 0 ] ) * ( r [ 0 ] - D [ 0 ] ) + ( r [ 1 ] - D [ 1 ] ) * ( r [ 1 ] - D [ 1 ] ) ) NEW_LINE if ( dis < q ) : NEW_LINE INDENT print ( " Point β ( " , D [ 0 ] , " , " , D [ 1 ] , " ) β is β inside β the β circumcircle " ) NEW_LINE DEDENT elif ( dis == q ) : NEW_LINE INDENT print ( " Point β ( " , D [ 0 ] , " , " , D [ 1 ] , " ) β lies β on β the β circumcircle " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " Point β ( " , D [ 0 ] , " , " , D [ 1 ] , " ) β lies β outside β the β circumcircle " ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT A = [ 2 , 8 ] NEW_LINE B = [ 2 , 1 ] NEW_LINE C = [ 4 , 5 ] NEW_LINE D = [ 3 , 0 ] NEW_LINE findPosition ( A , B , C , D ) NEW_LINE DEDENT |
Find the maximum angle at which we can tilt the bottle without spilling any water | Python3 program to find the maximum angle at which we can tilt the bottle without spilling any water ; Now we have the volume of rectangular prism a * a * b ; Now we have 2 cases ! ; Taking the tangent inverse of value d As we want to take out the required angle ; Taking the tangent inverse of value d As we want to take out the required angle ; As of now the angle is in radian . So we have to convert it in degree . ; Driver Code ; Enter the Base square side length ; Enter the Height of rectangular prism ; Enter the Base square side length | from math import * NEW_LINE def find_angle ( x , y , z ) : NEW_LINE INDENT volume = x * x * y ; NEW_LINE ans = 0 ; NEW_LINE if ( z < volume // 2 ) : NEW_LINE INDENT d = ( x * y * y ) / ( 2.0 * z ) ; NEW_LINE ans = atan ( d ) ; NEW_LINE DEDENT else : NEW_LINE INDENT z = volume - z ; NEW_LINE d = ( 2 * z ) / ( float ) ( x * x * x ) ; NEW_LINE ans = atan ( d ) ; NEW_LINE DEDENT ans = ( ans * 180 ) / 3.14159265 ; NEW_LINE return round ( ans , 4 ) ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT x = 12 ; NEW_LINE y = 21 ; NEW_LINE z = 10 ; NEW_LINE print ( find_angle ( x , y , z ) ) ; NEW_LINE DEDENT |
Count of distinct rectangles inscribed in an equilateral triangle | Function to return the count of rectangles when n is odd ; Calculating number of dots in vertical level ; Calculating number of ways to select two points in the horizontal level i ; Multiply both to obtain the number of rectangles formed at that level ; Calculating number of dots in vertical level ; Calculating number of ways to select two points in the horizontal level i ; Multiply both to obtain the number of rectangles formed at that level ; Function to return the count of rectangles when n is even ; Driver code ; If n is odd | def countOdd ( n ) : NEW_LINE INDENT coun = 0 NEW_LINE i = n - 2 NEW_LINE while ( i >= 1 ) : NEW_LINE INDENT if ( i & 1 ) : NEW_LINE INDENT m = int ( ( n - i ) / 2 ) NEW_LINE j = int ( ( i * ( i + 1 ) ) / 2 ) NEW_LINE coun += j * m NEW_LINE DEDENT else : NEW_LINE INDENT m = int ( ( ( n - 1 ) - i ) / 2 ) NEW_LINE j = int ( ( i * ( i + 1 ) ) / 2 ) NEW_LINE coun += j * m NEW_LINE DEDENT i -= 1 NEW_LINE DEDENT return coun NEW_LINE DEDENT def countEven ( n ) : NEW_LINE INDENT coun = 0 NEW_LINE i = n - 2 NEW_LINE while ( i >= 1 ) : NEW_LINE INDENT if ( i & 1 ) : NEW_LINE INDENT m = int ( ( ( n - 1 ) - i ) / 2 ) NEW_LINE j = int ( ( i * ( i + 1 ) ) / 2 ) NEW_LINE coun += j * m NEW_LINE DEDENT else : NEW_LINE INDENT m = int ( ( n - i ) / 2 ) NEW_LINE j = ( i * ( i + 1 ) ) // 2 NEW_LINE coun += j * m NEW_LINE DEDENT DEDENT return coun NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT n = 5 NEW_LINE if ( n & 1 ) : NEW_LINE INDENT print ( countOdd ( n ) ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( countEven ( n ) ) NEW_LINE DEDENT DEDENT |
Find same contacts in a list of contacts | Structure for storing contact details . ; A utility function to fill entries in adjacency matrix representation of graph ; Initialize the adjacency matrix ; Traverse through all contacts ; Add mat from i to j and vice versa , if possible . Since length of each contact field is at max some constant . ( say 30 ) so body execution of this for loop takes constant time . ; A recuesive function to perform DFS with vertex i as source ; Finds similar contacrs in an array of contacts ; vector for storing the solution ; Declare 2D adjaceny matrix for mats ; visited array to keep track of visited nodes ; Fill adjacency matrix ; Since , we made a graph with contacts as nodes with fields as links . Two nodes are linked if they represent the same person . So , total number of connected components and nodes in each component will be our answer . ; Add delimeter to separate nodes of one component from other . ; Print the solution ; Driver Code | class contact : NEW_LINE INDENT def __init__ ( self , field1 , field2 , field3 ) : NEW_LINE INDENT self . field1 = field1 NEW_LINE self . field2 = field2 NEW_LINE self . field3 = field3 NEW_LINE DEDENT DEDENT def buildGraph ( arr , n , mat ) : NEW_LINE INDENT for i in range ( n ) : NEW_LINE INDENT for j in range ( n ) : NEW_LINE INDENT mat [ i ] [ j ] = 0 NEW_LINE DEDENT DEDENT for i in range ( n ) : NEW_LINE INDENT for j in range ( i + 1 , n ) : NEW_LINE INDENT if ( arr [ i ] . field1 == arr [ j ] . field1 or arr [ i ] . field1 == arr [ j ] . field2 or arr [ i ] . field1 == arr [ j ] . field3 or arr [ i ] . field2 == arr [ j ] . field1 or arr [ i ] . field2 == arr [ j ] . field2 or arr [ i ] . field2 == arr [ j ] . field3 or arr [ i ] . field3 == arr [ j ] . field1 or arr [ i ] . field3 == arr [ j ] . field2 or arr [ i ] . field3 == arr [ j ] . field3 ) : NEW_LINE INDENT mat [ i ] [ j ] = 1 NEW_LINE mat [ j ] [ i ] = 1 NEW_LINE break NEW_LINE DEDENT DEDENT DEDENT DEDENT def DFSvisit ( i , mat , visited , sol , n ) : NEW_LINE INDENT visited [ i ] = True NEW_LINE sol . append ( i ) NEW_LINE for j in range ( n ) : NEW_LINE INDENT if ( mat [ i ] [ j ] and not visited [ j ] ) : NEW_LINE INDENT DFSvisit ( j , mat , visited , sol , n ) NEW_LINE DEDENT DEDENT DEDENT def findSameContacts ( arr , n ) : NEW_LINE INDENT sol = [ ] NEW_LINE mat = [ [ None ] * n for i in range ( n ) ] NEW_LINE visited = [ 0 ] * n NEW_LINE buildGraph ( arr , n , mat ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( not visited [ i ] ) : NEW_LINE INDENT DFSvisit ( i , mat , visited , sol , n ) NEW_LINE sol . append ( - 1 ) NEW_LINE DEDENT DEDENT for i in range ( len ( sol ) ) : NEW_LINE INDENT if ( sol [ i ] == - 1 ) : NEW_LINE INDENT print ( ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( sol [ i ] , end = " β " ) NEW_LINE DEDENT DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ contact ( " Gaurav " , " gaurav @ gmail . com " , " gaurav @ gfgQA . com " ) , contact ( " Lucky " , " lucky @ gmail . com " , " + 1234567" ) , contact ( " gaurav123" , " + 5412312" , " gaurav123 @ skype . com " ) , contact ( " gaurav1993" , " + 5412312" , " gaurav @ gfgQA . com " ) , contact ( " raja " , " + 2231210" , " raja @ gfg . com " ) , contact ( " bahubali " , " + 878312" , " raja " ) ] NEW_LINE n = len ( arr ) NEW_LINE findSameContacts ( arr , n ) NEW_LINE DEDENT |
Area of the biggest ellipse inscribed within a rectangle | Function to find the area of the ellipse ; The sides cannot be negative ; Area of the ellipse ; Driver code | def ellipse ( l , b ) : NEW_LINE INDENT if l < 0 or b < 0 : NEW_LINE INDENT return - 1 NEW_LINE DEDENT x = ( 3.14 * l * b ) / 4 NEW_LINE return x NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT l , b = 5 , 3 NEW_LINE print ( ellipse ( l , b ) ) NEW_LINE DEDENT |
Determine the number of squares of unit area that a given line will pass through . | Python3 program to determine the number of squares that line will pass through ; Function to return the required position ; Driver Code | from math import gcd NEW_LINE def noOfSquares ( x1 , y1 , x2 , y2 ) : NEW_LINE INDENT dx = abs ( x2 - x1 ) ; NEW_LINE dy = abs ( y2 - y1 ) ; NEW_LINE ans = dx + dy - gcd ( dx , dy ) ; NEW_LINE print ( ans ) ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT x1 = 1 ; y1 = 1 ; x2 = 4 ; y2 = 3 ; NEW_LINE noOfSquares ( x1 , y1 , x2 , y2 ) ; NEW_LINE DEDENT |
Count paths with distance equal to Manhattan distance | Function to return the value of nCk ; Since C ( n , k ) = C ( n , n - k ) ; Calculate value of [ n * ( n - 1 ) * -- - * ( n - k + 1 ) ] / [ k * ( k - 1 ) * -- - * 1 ] ; Function to return the number of paths ; Difference between the ' x ' coordinates of the given points ; Difference between the ' y ' coordinates of the given points ; Driver code | def binomialCoeff ( n , k ) : NEW_LINE INDENT res = 1 NEW_LINE if ( k > n - k ) : NEW_LINE INDENT k = n - k NEW_LINE DEDENT for i in range ( k ) : NEW_LINE INDENT res *= ( n - i ) NEW_LINE res //= ( i + 1 ) NEW_LINE DEDENT return res NEW_LINE DEDENT def countPaths ( x1 , y1 , x2 , y2 ) : NEW_LINE INDENT m = abs ( x1 - x2 ) NEW_LINE n = abs ( y1 - y2 ) NEW_LINE return ( binomialCoeff ( m + n , n ) ) NEW_LINE DEDENT x1 , y1 , x2 , y2 = 2 , 3 , 4 , 5 NEW_LINE print ( countPaths ( x1 , y1 , x2 , y2 ) ) NEW_LINE |
Find the area of largest circle inscribed in ellipse | Python3 program implementation of above approach ; Area of the Reuleaux triangle ; Driver Code | import math NEW_LINE def areaCircle ( b ) : NEW_LINE INDENT area = math . pi * b * b NEW_LINE return area NEW_LINE DEDENT a = 10 NEW_LINE b = 8 NEW_LINE print ( areaCircle ( b ) ) NEW_LINE |
Section formula for 3 D | Function to find the section of the line ; Applying section formula ; Printing result ; Driver code | def section ( x1 , x2 , y1 , y2 , z1 , z2 , m , n ) : NEW_LINE INDENT x = ( ( m * x2 ) + ( n * x1 ) ) / ( m + n ) NEW_LINE y = ( ( m * y2 ) + ( n * y1 ) ) / ( m + n ) NEW_LINE z = ( ( m * z2 ) + ( n * z1 ) ) / ( m + n ) NEW_LINE print ( " ( " , x , " , " , y , " , " , z , " ) " ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT x1 = 2 NEW_LINE x2 = 4 NEW_LINE y1 = - 1 NEW_LINE y2 = 3 NEW_LINE z1 = 4 NEW_LINE z2 = 2 NEW_LINE m = 2 NEW_LINE n = 3 NEW_LINE section ( x1 , x2 , y1 , y2 , z1 , z2 , m , n ) NEW_LINE DEDENT |
Program to find the Circumcircle of any regular polygon | Python3 Program to find the radius of the circumcircle of the given polygon ; Function to find the radius of the circumcircle ; these cannot be negative ; Radius of the circumcircle ; Return the radius ; Driver code ; Find the radius of the circumcircle | from math import * NEW_LINE def findRadiusOfcircumcircle ( n , a ) : NEW_LINE INDENT if n < 0 or a < 0 : NEW_LINE INDENT return - 1 NEW_LINE DEDENT radius = a / sqrt ( 2 - ( 2 * cos ( 360 / n ) ) ) NEW_LINE return radius NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT n , a = 5 , 6 NEW_LINE print ( round ( findRadiusOfcircumcircle ( n , a ) , 5 ) ) NEW_LINE DEDENT |
Program to find the Radius of the incircle of the triangle | Function to find the radius of the incircle ; the sides cannot be negative ; semi - perimeter of the circle ; area of the triangle ; Radius of the incircle ; Return the radius ; Driver code ; Get the sides of the triangle ; Find the radius of the incircle | def findRadiusOfIncircle ( a , b , c ) : NEW_LINE INDENT if ( a < 0 or b < 0 or c < 0 ) : NEW_LINE INDENT return - 1 NEW_LINE DEDENT p = ( a + b + c ) / 2 NEW_LINE area = sqrt ( p * ( p - a ) * ( p - b ) * ( p - c ) ) NEW_LINE radius = area / p NEW_LINE return radius NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT a , b , c = 2 , 2 , 3 NEW_LINE print ( round ( findRadiusOfIncircle ( a , b , c ) , 6 ) ) NEW_LINE DEDENT |
Find area of triangle if two vectors of two adjacent sides are given | Python code to calculate area of triangle if vectors of 2 adjacent sides are given ; function to calculate area of triangle ; driver code | import math NEW_LINE def area ( x1 , y1 , z1 , x2 , y2 , z2 ) : NEW_LINE INDENT area = math . sqrt ( ( y1 * z2 - y2 * z1 ) ** 2 + ( x1 * z2 - x2 * z1 ) ** 2 + ( x1 * y2 - x2 * y1 ) ** 2 ) NEW_LINE area = area / 2 NEW_LINE return area NEW_LINE DEDENT def main ( ) : NEW_LINE INDENT x1 = - 2 NEW_LINE y1 = 0 NEW_LINE z1 = - 5 NEW_LINE x2 = 1 NEW_LINE y2 = - 2 NEW_LINE z2 = - 1 NEW_LINE a = area ( x1 , y1 , z1 , x2 , y2 , z2 ) NEW_LINE print ( " Area β = β " , a ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT main ( ) NEW_LINE DEDENT |
Largest trapezoid that can be inscribed in a semicircle | Python 3 Program to find the biggest trapezoid which can be inscribed within the semicircle ; Function to find the area of the biggest trapezoid ; the radius cannot be negative ; area of the trapezoid ; Driver code | from math import * NEW_LINE def trapezoidarea ( r ) : NEW_LINE INDENT if r < 0 : NEW_LINE INDENT return - 1 NEW_LINE DEDENT a = ( 3 * sqrt ( 3 ) * pow ( r , 2 ) ) / 4 NEW_LINE return a NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT r = 5 NEW_LINE print ( round ( trapezoidarea ( r ) , 3 ) ) NEW_LINE DEDENT |
Largest rectangle that can be inscribed in a semicircle | Function to find the area of the biggest rectangle ; the radius cannot be negative ; area of the rectangle ; Driver Code | def rectanglearea ( r ) : NEW_LINE INDENT if r < 0 : NEW_LINE INDENT return - 1 NEW_LINE DEDENT a = r * r NEW_LINE return a NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT r = 5 NEW_LINE DEDENT |
Maximum distinct lines passing through a single point | Python3 program to find maximum number of lines which can pass through a single point ; function to find maximum lines which passes through a single point ; Driver Code | import sys NEW_LINE def maxLines ( n , x1 , y1 , x2 , y2 ) : NEW_LINE INDENT s = [ ] ; NEW_LINE slope = sys . maxsize ; NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( x1 [ i ] == x2 [ i ] ) : NEW_LINE INDENT slope = sys . maxsize ; NEW_LINE DEDENT else : NEW_LINE INDENT slope = ( y2 [ i ] - y1 [ i ] ) * 1.0 / ( x2 [ i ] - x1 [ i ] ) * 1.0 ; NEW_LINE DEDENT s . append ( slope ) ; NEW_LINE DEDENT return len ( s ) ; NEW_LINE DEDENT n = 2 ; NEW_LINE x1 = [ 1 , 2 ] ; NEW_LINE y1 = [ 1 , 2 ] ; NEW_LINE x2 = [ 2 , 4 ] ; NEW_LINE y2 = [ 2 , 10 ] ; NEW_LINE print ( maxLines ( n , x1 , y1 , x2 , y2 ) ) ; NEW_LINE |
Find area of parallelogram if vectors of two adjacent sides are given | Python code to calculate area of parallelogram if vectors of 2 adjacent sides are given ; Function to calculate area of parallelogram ; driver code | import math NEW_LINE def area ( x1 , y1 , z1 , x2 , y2 , z2 ) : NEW_LINE INDENT area = math . sqrt ( ( y1 * z2 - y2 * z1 ) ** 2 + ( x1 * z2 - x2 * z1 ) ** 2 + ( x1 * y2 - x2 * y1 ) ** 2 ) NEW_LINE return area NEW_LINE DEDENT def main ( ) : NEW_LINE INDENT x1 = 3 NEW_LINE y1 = 1 NEW_LINE z1 = - 2 NEW_LINE x2 = 1 NEW_LINE y2 = - 3 NEW_LINE z2 = 4 NEW_LINE a = area ( x1 , y1 , z1 , x2 , y2 , z2 ) NEW_LINE print ( " Area β = β " , a ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT main ( ) NEW_LINE DEDENT |
Maximum possible intersection by moving centers of line segments | Function to print the maximum intersection ; Case 1 ; Case 2 ; Case 3 ; Driver Code | def max_intersection ( center , length , k ) : NEW_LINE INDENT center . sort ( ) ; NEW_LINE if ( center [ 2 ] - center [ 0 ] >= 2 * k + length ) : NEW_LINE INDENT return 0 ; NEW_LINE DEDENT elif ( center [ 2 ] - center [ 0 ] >= 2 * k ) : NEW_LINE INDENT return ( 2 * k - ( center [ 2 ] - center [ 0 ] - length ) ) ; NEW_LINE DEDENT else : NEW_LINE INDENT return length ; NEW_LINE DEDENT DEDENT center = [ 1 , 2 , 3 ] ; NEW_LINE L = 1 ; NEW_LINE K = 1 ; NEW_LINE print ( max_intersection ( center , L , K ) ) ; NEW_LINE |
Haversine formula to find distance between two points on a sphere | Python 3 program for the haversine formula ; distance between latitudes and longitudes ; convert to radians ; apply formulae ; Driver code | import math NEW_LINE def haversine ( lat1 , lon1 , lat2 , lon2 ) : NEW_LINE INDENT dLat = ( lat2 - lat1 ) * math . pi / 180.0 NEW_LINE dLon = ( lon2 - lon1 ) * math . pi / 180.0 NEW_LINE lat1 = ( lat1 ) * math . pi / 180.0 NEW_LINE lat2 = ( lat2 ) * math . pi / 180.0 NEW_LINE a = ( pow ( math . sin ( dLat / 2 ) , 2 ) + pow ( math . sin ( dLon / 2 ) , 2 ) * math . cos ( lat1 ) * math . cos ( lat2 ) ) ; NEW_LINE rad = 6371 NEW_LINE c = 2 * math . asin ( math . sqrt ( a ) ) NEW_LINE return rad * c NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT lat1 = 51.5007 NEW_LINE lon1 = 0.1246 NEW_LINE lat2 = 40.6892 NEW_LINE lon2 = 74.0445 NEW_LINE print ( haversine ( lat1 , lon1 , lat2 , lon2 ) , " K . M . " ) NEW_LINE DEDENT |
Heptagonal number | Function to find nth Heptagonal number ; Driver Code | def heptagonalNumber ( n ) : NEW_LINE INDENT return ( ( 5 * n * n ) - ( 3 * n ) ) // 2 NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT n = 2 NEW_LINE print ( heptagonalNumber ( n ) ) NEW_LINE n = 15 NEW_LINE print ( heptagonalNumber ( n ) ) NEW_LINE DEDENT |
Icosidigonal number | Function to calculate Icosidigonal number ; Formula for finding nth Icosidigonal number ; Driver Code | def icosidigonal_num ( n ) : NEW_LINE INDENT return ( 20 * n * n - 18 * n ) // 2 NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT n = 4 NEW_LINE print ( n , " th β Icosidigonal β " + " number β : β " , icosidigonal_num ( n ) ) NEW_LINE n = 8 NEW_LINE print ( n , " th β Icosidigonal β " + " number β : β " , icosidigonal_num ( n ) ) NEW_LINE DEDENT |
Hypercube Graph | function to find power of 2 ; Dricer code | def power ( n ) : NEW_LINE INDENT if n == 1 : NEW_LINE INDENT return 2 NEW_LINE DEDENT return 2 * power ( n - 1 ) NEW_LINE DEDENT n = 4 NEW_LINE print ( power ( n ) ) NEW_LINE |
Reflection of a point at 180 degree rotation of another point | Python3 Program for find the 180 degree reflection of one point around another point . ; Driver Code | def findPoint ( x1 , y1 , x2 , y2 ) : NEW_LINE INDENT print ( " ( " , 2 * x2 - x1 , " , " , 2 * y2 - y1 , " ) " ) ; NEW_LINE DEDENT x1 = 0 ; NEW_LINE y1 = 0 ; NEW_LINE x2 = 1 ; NEW_LINE y2 = 1 ; NEW_LINE findPoint ( x1 , y1 , x2 , y2 ) ; NEW_LINE |
Program to check if the points are parallel to X axis or Y axis | To check for parallel line ; checking for parallel to X and Y axis condition ; To display the output ; Driver 's Code | def parallel ( n , a ) : NEW_LINE INDENT x = True ; NEW_LINE y = True ; NEW_LINE for i in range ( n - 1 ) : NEW_LINE INDENT if ( a [ i ] [ 0 ] != a [ i + 1 ] [ 0 ] ) : NEW_LINE INDENT x = False ; NEW_LINE DEDENT if ( a [ i ] [ 1 ] != a [ i + 1 ] [ 1 ] ) : NEW_LINE INDENT y = False ; NEW_LINE DEDENT DEDENT if ( x ) : NEW_LINE INDENT print ( " Parallel β to β Y β Axis " ) ; NEW_LINE DEDENT elif ( y ) : NEW_LINE INDENT print ( " Parallel β to β X β Axis " ) ; NEW_LINE DEDENT else : NEW_LINE INDENT print ( " Not β Parallel β to β X β and β Y β Axis " ) ; NEW_LINE DEDENT DEDENT a = [ [ 1 , 2 ] , [ 1 , 4 ] , [ 1 , 6 ] , [ 1 , 0 ] ] ; NEW_LINE n = len ( a ) ; NEW_LINE parallel ( n , a ) ; NEW_LINE |
Triangular Matchstick Number | Python program to find X - th triangular matchstick number ; Driver code | def numberOfSticks ( x ) : NEW_LINE INDENT return ( 3 * x * ( x + 1 ) ) / 2 NEW_LINE DEDENT print ( int ( numberOfSticks ( 7 ) ) ) NEW_LINE |
Total area of two overlapping rectangles | Python program to find total area of two overlapping Rectangles Returns Total Area of two overlap rectangles ; Area of 1 st Rectangle ; Area of 2 nd Rectangle ; Length of intersecting part i . e start from max ( l1 [ x ] , l2 [ x ] ) of x - coordinate and end at min ( r1 [ x ] , r2 [ x ] ) x - coordinate by subtracting start from end we get required lengths ; Driver 's Code ; Function call | def overlappingArea ( l1 , r1 , l2 , r2 ) : NEW_LINE INDENT x = 0 NEW_LINE y = 1 NEW_LINE area1 = abs ( l1 [ x ] - r1 [ x ] ) * abs ( l1 [ y ] - r1 [ y ] ) NEW_LINE area2 = abs ( l2 [ x ] - r2 [ x ] ) * abs ( l2 [ y ] - r2 [ y ] ) NEW_LINE x_dist = ( min ( r1 [ x ] , r2 [ x ] ) - max ( l1 [ x ] , l2 [ x ] ) ) NEW_LINE y_dist = ( min ( r1 [ y ] , r2 [ y ] ) - max ( l1 [ y ] , l2 [ y ] ) ) NEW_LINE areaI = 0 NEW_LINE if x_dist > 0 and y_dist > 0 : NEW_LINE INDENT areaI = x_dist * y_dist NEW_LINE DEDENT return ( area1 + area2 - areaI ) NEW_LINE DEDENT l1 = [ 2 , 2 ] NEW_LINE r1 = [ 5 , 7 ] NEW_LINE l2 = [ 3 , 4 ] NEW_LINE r2 = [ 6 , 9 ] NEW_LINE print ( overlappingArea ( l1 , r1 , l2 , r2 ) ) NEW_LINE |
Area of square Circumscribed by Circle | Function to find area of square ; Radius of a circle ; Call Function to find an area of square | def find_Area ( r ) : NEW_LINE INDENT return ( 2 * r * r ) NEW_LINE DEDENT r = 3 NEW_LINE print ( " β Area β of β square β = β " , find_Area ( r ) ) NEW_LINE |
Check whether triangle is valid or not if sides are given | function to check if three sides form a triangle or not ; check condition ; driver code ; function calling and print output | def checkValidity ( a , b , c ) : NEW_LINE INDENT if ( a + b <= c ) or ( a + c <= b ) or ( b + c <= a ) : NEW_LINE INDENT return False NEW_LINE DEDENT else : NEW_LINE INDENT return True NEW_LINE DEDENT DEDENT a = 7 NEW_LINE b = 10 NEW_LINE c = 5 NEW_LINE if checkValidity ( a , b , c ) : NEW_LINE INDENT print ( " Valid " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " Invalid " ) NEW_LINE DEDENT |
Print Longest Palindromic Subsequence | Returns LCS X and Y ; Following steps build L [ m + 1 ] [ n + 1 ] in bottom up fashion . Note that L [ i ] [ j ] contains length of LCS of X [ 0. . i - 1 ] and Y [ 0. . j - 1 ] ; Following code is used to print LCS ; Create a string length index + 1 and fill it with \ 0 ; Start from the right - most - bottom - most corner and one by one store characters in lcs [ ] ; If current character in X [ ] and Y are same , then current character is part of LCS ; Put current character in result ; reduce values of i , j and index ; If not same , then find the larger of two and go in the direction of larger value ; Returns longest palindromic subsequence of str ; Find reverse of str ; Return LCS of str and its reverse ; Driver Code | def lcs_ ( X , Y ) : NEW_LINE INDENT m = len ( X ) NEW_LINE n = len ( Y ) NEW_LINE L = [ [ 0 ] * ( n + 1 ) ] * ( m + 1 ) NEW_LINE for i in range ( n + 1 ) : NEW_LINE INDENT for j in range ( n + 1 ) : NEW_LINE INDENT if ( i == 0 or j == 0 ) : NEW_LINE INDENT L [ i ] [ j ] = 0 ; NEW_LINE DEDENT elif ( X [ i - 1 ] == Y [ j - 1 ] ) : NEW_LINE INDENT L [ i ] [ j ] = L [ i - 1 ] [ j - 1 ] + 1 ; NEW_LINE DEDENT else : NEW_LINE INDENT L [ i ] [ j ] = max ( L [ i - 1 ] [ j ] , L [ i ] [ j - 1 ] ) ; NEW_LINE DEDENT DEDENT DEDENT index = L [ m ] [ n ] ; NEW_LINE lcs = [ " " ] * ( index + 1 ) NEW_LINE i , j = m , n NEW_LINE while ( i > 0 and j > 0 ) : NEW_LINE INDENT if ( X [ i - 1 ] == Y [ j - 1 ] ) : NEW_LINE INDENT lcs [ index - 1 ] = X [ i - 1 ] NEW_LINE i -= 1 NEW_LINE j -= 1 NEW_LINE index -= 1 NEW_LINE DEDENT elif ( L [ i - 1 ] [ j ] > L [ i ] [ j - 1 ] ) : NEW_LINE INDENT i -= 1 NEW_LINE DEDENT else : NEW_LINE INDENT j -= 1 NEW_LINE DEDENT DEDENT ans = " " NEW_LINE for x in range ( len ( lcs ) ) : NEW_LINE INDENT ans += lcs [ x ] NEW_LINE DEDENT return ans NEW_LINE DEDENT def longestPalSubseq ( string ) : NEW_LINE INDENT rev = string [ : : - 1 ] NEW_LINE return lcs_ ( string , rev ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT string = " GEEKSFORGEEKS " ; NEW_LINE print ( longestPalSubseq ( string ) ) NEW_LINE DEDENT |
Find the Surface area of a 3D figure | Declaring the size of the matrix ; Absolute Difference between the height of two consecutive blocks ; Function To calculate the Total surfaceArea . ; Traversing the matrix . ; If we are traveling the topmost row in the matrix , we declare the wall above it as 0 as there is no wall above it . ; If we are traveling the leftmost column in the matrix , we declare the wall left to it as 0 as there is no wall left it . ; If its not the topmost row ; If its not the leftmost column ; Summing up the contribution of by the current block ; If its the rightmost block of the matrix it will contribute area equal to its height as a wall on the right of the figure ; If its the lowest block of the matrix it will contribute area equal to its height as a wall on the bottom of the figure ; Adding the contribution by the base and top of the figure ; Driver Code | M = 3 ; NEW_LINE N = 3 ; NEW_LINE def contribution_height ( current , previous ) : NEW_LINE INDENT return abs ( current - previous ) ; NEW_LINE DEDENT def surfaceArea ( A ) : NEW_LINE INDENT ans = 0 ; NEW_LINE for i in range ( N ) : NEW_LINE INDENT for j in range ( M ) : NEW_LINE INDENT up = 0 ; NEW_LINE left = 0 ; NEW_LINE if ( i > 0 ) : NEW_LINE INDENT up = A [ i - 1 ] [ j ] ; NEW_LINE DEDENT if ( j > 0 ) : NEW_LINE INDENT left = A [ i ] [ j - 1 ] ; NEW_LINE DEDENT ans += contribution_height ( A [ i ] [ j ] , up ) + contribution_height ( A [ i ] [ j ] , left ) ; NEW_LINE if ( i == N - 1 ) : NEW_LINE INDENT ans += A [ i ] [ j ] ; NEW_LINE DEDENT if ( j == M - 1 ) : NEW_LINE INDENT ans += A [ i ] [ j ] ; NEW_LINE DEDENT DEDENT DEDENT ans += N * M * 2 ; NEW_LINE return ans ; NEW_LINE DEDENT A = [ [ 1 , 3 , 4 ] , [ 2 , 2 , 3 ] , [ 1 , 2 , 4 ] ] ; NEW_LINE print ( surfaceArea ( A ) ) ; NEW_LINE |
Program to calculate area and volume of a Tetrahedron | Python3 Program to Calculate area of tetrahedron ; ; Driver Code | import math NEW_LINE / * Utility Function * / NEW_LINE def area_of_tetrahedron ( side ) : NEW_LINE INDENT return ( math . sqrt ( 3 ) * ( side * side ) ) ; NEW_LINE DEDENT side = 3 ; NEW_LINE print ( " Area β of β Tetrahedron β = β " , round ( area_of_tetrahedron ( side ) , 4 ) ) ; NEW_LINE |
Program to calculate area and volume of a Tetrahedron | Python code to find the volume of a tetrahedron ; Function to calculate volume ; Driver Code | import math NEW_LINE def vol_tetra ( side ) : NEW_LINE INDENT volume = ( side ** 3 / ( 6 * math . sqrt ( 2 ) ) ) NEW_LINE return round ( volume , 2 ) NEW_LINE DEDENT side = 3 NEW_LINE vol = vol_tetra ( side ) NEW_LINE print ( vol ) NEW_LINE |
Counting pairs when a person can form pair with at most one | Number of ways in which participant can take part . ; Driver code | def numberOfWays ( x ) : NEW_LINE INDENT dp = [ ] NEW_LINE dp . append ( 1 ) NEW_LINE dp . append ( 1 ) NEW_LINE for i in range ( 2 , x + 1 ) : NEW_LINE INDENT dp . append ( dp [ i - 1 ] + ( i - 1 ) * dp [ i - 2 ] ) NEW_LINE DEDENT return ( dp [ x ] ) NEW_LINE DEDENT x = 3 NEW_LINE print ( numberOfWays ( x ) ) NEW_LINE |
Program to find slope of a line | Python3 program to find slope ; Function to find the slope of a straight line ; Driver code | import sys NEW_LINE def slope ( x1 , y1 , x2 , y2 ) : NEW_LINE INDENT if x1 == x2 : NEW_LINE INDENT return ( sys . maxsize ) NEW_LINE DEDENT return ( ( y2 - y1 ) / ( x2 - x1 ) ) NEW_LINE DEDENT x1 = 4 NEW_LINE y1 = 2 NEW_LINE x2 = 2 NEW_LINE y2 = 5 NEW_LINE print ( " Slope β is β : " , slope ( 4 , 2 , 2 , 5 ) ) NEW_LINE |
Program to calculate area and perimeter of equilateral triangle | Python3 program to calculate Area and Perimeter of equilateral Triangle ; Function to calculate Area of equilateral triangle ; Function to calculate Perimeter of equilateral triangle ; Driver code | from math import * NEW_LINE def area_equilateral ( side ) : NEW_LINE INDENT area = ( sqrt ( 3 ) / 4 ) * side * side NEW_LINE print ( " Area β of β Equilateral β Triangle : β % β f " % area ) NEW_LINE DEDENT def perimeter ( side ) : NEW_LINE INDENT perimeter = 3 * side NEW_LINE print ( " Perimeter β of β Equilateral β Triangle : β % β f " % perimeter ) NEW_LINE DEDENT side = 4 NEW_LINE area_equilateral ( side ) NEW_LINE perimeter ( side ) NEW_LINE |
Maximum integral co | Making set of coordinates such that any two points are non - integral distance apart ; Used to avoid duplicates in result ; Driver code | def printSet ( x , y ) : NEW_LINE INDENT arr = [ ] NEW_LINE for i in range ( min ( x , y ) + 1 ) : NEW_LINE INDENT pq = [ i , min ( x , y ) - i ] NEW_LINE arr . append ( pq ) NEW_LINE DEDENT for it in arr : NEW_LINE INDENT print ( it [ 0 ] , it [ 1 ] ) NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT x = 4 NEW_LINE y = 4 NEW_LINE printSet ( x , y ) NEW_LINE DEDENT |
Program for Volume and Surface Area of Cuboid | utility function ; driver function | def volumeCuboid ( l , h , w ) : NEW_LINE INDENT return ( l * h * w ) NEW_LINE DEDENT def surfaceAreaCuboid ( l , h , w ) : NEW_LINE INDENT return ( 2 * l * w + 2 * w * h + 2 * l * h ) NEW_LINE DEDENT l = 1 NEW_LINE h = 5 NEW_LINE w = 7 NEW_LINE print ( " Volume β = " , volumeCuboid ( l , h , w ) ) NEW_LINE print ( " Total β Surface β Area β = " , surfaceAreaCuboid ( l , h , w ) ) NEW_LINE |
Program to find Circumference of a Circle | Python3 code to find circumference of circle ; utility function ; driver function | PI = 3.1415 NEW_LINE def circumference ( r ) : NEW_LINE INDENT return ( 2 * PI * r ) NEW_LINE DEDENT print ( ' % .3f ' % circumference ( 5 ) ) NEW_LINE |
Program to check if three points are collinear | function to check if point collinear or not ; Driver Code | def collinear ( x1 , y1 , x2 , y2 , x3 , y3 ) : NEW_LINE INDENT if ( ( y3 - y2 ) * ( x2 - x1 ) == ( y2 - y1 ) * ( x3 - x2 ) ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT DEDENT x1 , x2 , x3 , y1 , y2 , y3 = 1 , 1 , 0 , 1 , 6 , 9 NEW_LINE collinear ( x1 , y1 , x2 , y2 , x3 , y3 ) ; NEW_LINE |
Number of rectangles in N * M grid | Python3 program to count number of rectangles in a n x m grid ; Driver code | def rectCount ( n , m ) : NEW_LINE INDENT return ( m * n * ( n + 1 ) * ( m + 1 ) ) // 4 NEW_LINE DEDENT n , m = 5 , 4 NEW_LINE print ( rectCount ( n , m ) ) NEW_LINE |
Number of unique rectangles formed using N unit squares | Python3 program to count rotationally equivalent rectangles with n unit squares ; height >= length is maintained ; Driver code | import math NEW_LINE def countRect ( n ) : NEW_LINE INDENT ans = 0 NEW_LINE for length in range ( 1 , int ( math . sqrt ( n ) ) + 1 ) : NEW_LINE INDENT height = length NEW_LINE while ( height * length <= n ) : NEW_LINE INDENT ans += 1 NEW_LINE height += 1 NEW_LINE DEDENT DEDENT return ans NEW_LINE DEDENT n = 5 NEW_LINE print ( countRect ( n ) ) NEW_LINE |
Find the Missing Point of Parallelogram | Main method ; coordinates of A ; coordinates of B ; coordinates of C | if __name__ == " _ _ main _ _ " : NEW_LINE INDENT ax , ay = 5 , 0 NEW_LINE bx , by = 1 , 1 NEW_LINE cx , cy = 2 , 5 NEW_LINE print ( ax + cx - bx , " , " , ay + cy - by ) NEW_LINE DEDENT |
Represent a given set of points by the best possible straight line | function to calculate m and c that best fit points represented by x [ ] and y [ ] ; Driver main function | def bestApproximate ( x , y , n ) : NEW_LINE INDENT sum_x = 0 NEW_LINE sum_y = 0 NEW_LINE sum_xy = 0 NEW_LINE sum_x2 = 0 NEW_LINE for i in range ( 0 , n ) : NEW_LINE INDENT sum_x += x [ i ] NEW_LINE sum_y += y [ i ] NEW_LINE sum_xy += x [ i ] * y [ i ] NEW_LINE sum_x2 += pow ( x [ i ] , 2 ) NEW_LINE DEDENT m = ( float ) ( ( n * sum_xy - sum_x * sum_y ) / ( n * sum_x2 - pow ( sum_x , 2 ) ) ) ; NEW_LINE c = ( float ) ( sum_y - m * sum_x ) / n ; NEW_LINE print ( " m β = β " , m ) ; NEW_LINE print ( " c β = β " , c ) ; NEW_LINE DEDENT x = [ 1 , 2 , 3 , 4 , 5 ] NEW_LINE y = [ 14 , 27 , 40 , 55 , 68 ] NEW_LINE n = len ( x ) NEW_LINE bestApproximate ( x , y , n ) NEW_LINE |
Check for star graph | define the size of incidence matrix ; def to find star graph ; initialize number of vertex with deg 1 and n - 1 ; check for S1 ; check for S2 ; check for Sn ( n > 2 ) ; Driver code | size = 4 NEW_LINE def checkStar ( mat ) : NEW_LINE INDENT global size NEW_LINE vertexD1 = 0 NEW_LINE vertexDn_1 = 0 NEW_LINE if ( size == 1 ) : NEW_LINE INDENT return ( mat [ 0 ] [ 0 ] == 0 ) NEW_LINE DEDENT if ( size == 2 ) : NEW_LINE INDENT return ( mat [ 0 ] [ 0 ] == 0 and mat [ 0 ] [ 1 ] == 1 and mat [ 1 ] [ 0 ] == 1 and mat [ 1 ] [ 1 ] == 0 ) NEW_LINE DEDENT for i in range ( 0 , size ) : NEW_LINE INDENT degreeI = 0 NEW_LINE for j in range ( 0 , size ) : NEW_LINE INDENT if ( mat [ i ] [ j ] ) : NEW_LINE INDENT degreeI = degreeI + 1 NEW_LINE DEDENT DEDENT if ( degreeI == 1 ) : NEW_LINE INDENT vertexD1 = vertexD1 + 1 NEW_LINE DEDENT elif ( degreeI == size - 1 ) : NEW_LINE INDENT vertexDn_1 = vertexDn_1 + 1 NEW_LINE DEDENT DEDENT return ( vertexD1 == ( size - 1 ) and vertexDn_1 == 1 ) NEW_LINE DEDENT mat = [ [ 0 , 1 , 1 , 1 ] , [ 1 , 0 , 0 , 0 ] , [ 1 , 0 , 0 , 0 ] , [ 1 , 0 , 0 , 0 ] ] NEW_LINE if ( checkStar ( mat ) ) : NEW_LINE INDENT print ( " Star β Graph " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " Not β a β Star β Graph " ) NEW_LINE DEDENT |
Dynamic Convex hull | Adding Points to an Existing Convex Hull | Python 3 program to add given a point p to a given convext hull . The program assumes that the point of given convext hull are in anti - clockwise order . ; checks whether the point crosses the convex hull or not ; Returns the square of distance between two input points ; Checks whether the point is inside the convex hull or not ; Initialize the centroid of the convex hull ; Multiplying with n to avoid floating point arithmetic . ; if the mid and the given point lies always on the same side w . r . t every edge of the convex hull , then the point lies inside the convex hull ; Adds a point p to given convex hull a [ ] ; If point is inside p ; point having minimum distance from the point p ; Find the upper tangent ; Find the lower tangent ; Initialize result ; making the final hull by traversing points from up to low of given convex hull . ; Modify the original vector ; Driver code ; the set of points in the convex hull ; Print the modified Convex Hull | import copy NEW_LINE def orientation ( a , b , c ) : NEW_LINE INDENT res = ( ( b [ 1 ] - a [ 1 ] ) * ( c [ 0 ] - b [ 0 ] ) - ( c [ 1 ] - b [ 1 ] ) * ( b [ 0 ] - a [ 0 ] ) ) NEW_LINE if ( res == 0 ) : NEW_LINE INDENT return 0 ; NEW_LINE DEDENT if ( res > 0 ) : NEW_LINE INDENT return 1 ; NEW_LINE DEDENT return - 1 ; NEW_LINE DEDENT def sqDist ( p1 , p2 ) : NEW_LINE INDENT return ( ( p1 [ 0 ] - p2 [ 0 ] ) * ( p1 [ 0 ] - p2 [ 0 ] ) + ( p1 [ 1 ] - p2 [ 1 ] ) * ( p1 [ 1 ] - p2 [ 1 ] ) ) ; NEW_LINE DEDENT def inside ( a , p ) : NEW_LINE INDENT mid = [ 0 , 0 ] NEW_LINE n = len ( a ) NEW_LINE p [ 0 ] *= n ; NEW_LINE p [ 1 ] *= n ; NEW_LINE for i in range ( n ) : NEW_LINE INDENT mid [ 0 ] += a [ i ] [ 0 ] ; NEW_LINE mid [ 1 ] += a [ i ] [ 1 ] ; NEW_LINE a [ i ] [ 0 ] *= n ; NEW_LINE a [ i ] [ 1 ] *= n ; NEW_LINE DEDENT for i in range ( n ) : NEW_LINE INDENT j = ( i + 1 ) % n ; NEW_LINE x1 = a [ i ] [ 0 ] NEW_LINE x2 = a [ j ] [ 0 ] NEW_LINE y1 = a [ i ] [ 1 ] NEW_LINE y2 = a [ j ] [ 1 ] NEW_LINE a1 = y1 - y2 ; NEW_LINE b1 = x2 - x1 ; NEW_LINE c1 = x1 * y2 - y1 * x2 ; NEW_LINE for_mid = a1 * mid [ 0 ] + b1 * mid [ 1 ] + c1 ; NEW_LINE for_p = a1 * p [ 0 ] + b1 * p [ 1 ] + c1 ; NEW_LINE if ( for_mid * for_p < 0 ) : NEW_LINE INDENT return False ; NEW_LINE DEDENT DEDENT return True ; NEW_LINE DEDENT def addPoint ( a , p ) : NEW_LINE INDENT arr = copy . deepcopy ( a ) NEW_LINE prr = p . copy ( ) NEW_LINE if ( inside ( arr , prr ) ) : NEW_LINE INDENT return ; NEW_LINE DEDENT ind = 0 ; NEW_LINE n = len ( a ) NEW_LINE for i in range ( 1 , n ) : NEW_LINE INDENT if ( sqDist ( p , a [ i ] ) < sqDist ( p , a [ ind ] ) ) : NEW_LINE INDENT ind = i NEW_LINE DEDENT DEDENT up = ind ; NEW_LINE while ( orientation ( p , a [ up ] , a [ ( up + 1 ) % n ] ) >= 0 ) : NEW_LINE INDENT up = ( up + 1 ) % n ; NEW_LINE DEDENT low = ind ; NEW_LINE while ( orientation ( p , a [ low ] , a [ ( n + low - 1 ) % n ] ) <= 0 ) : NEW_LINE INDENT low = ( n + low - 1 ) % n NEW_LINE DEDENT ret = [ ] NEW_LINE curr = up ; NEW_LINE ret . append ( a [ curr ] ) ; NEW_LINE while ( curr != low ) : NEW_LINE INDENT curr = ( curr + 1 ) % n ; NEW_LINE ret . append ( a [ curr ] ) ; NEW_LINE DEDENT ret . append ( p ) ; NEW_LINE a . clear ( ) ; NEW_LINE for i in range ( len ( ret ) ) : NEW_LINE INDENT a . append ( ret [ i ] ) ; NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT a = [ ] NEW_LINE a . append ( [ 0 , 0 ] ) ; NEW_LINE a . append ( [ 3 , - 1 ] ) ; NEW_LINE a . append ( [ 4 , 5 ] ) ; NEW_LINE a . append ( [ - 1 , 4 ] ) ; NEW_LINE n = len ( a ) NEW_LINE p = [ 100 , 100 ] NEW_LINE addPoint ( a , p ) ; NEW_LINE for e in a : NEW_LINE INDENT print ( " ( " , e [ 0 ] , " , β " , e [ 1 ] , " ) β " , end = " β " ) NEW_LINE DEDENT DEDENT |
Find all angles of a given triangle | Python3 code to find all three angles of a triangle given coordinate of all three vertices ; returns square of distance b / w two points ; Square of lengths be a2 , b2 , c2 ; length of sides be a , b , c ; From Cosine law ; Converting to degree ; printing all the angles ; Driver code | import math NEW_LINE def lengthSquare ( X , Y ) : NEW_LINE INDENT xDiff = X [ 0 ] - Y [ 0 ] NEW_LINE yDiff = X [ 1 ] - Y [ 1 ] NEW_LINE return xDiff * xDiff + yDiff * yDiff NEW_LINE DEDENT def printAngle ( A , B , C ) : NEW_LINE INDENT a2 = lengthSquare ( B , C ) NEW_LINE b2 = lengthSquare ( A , C ) NEW_LINE c2 = lengthSquare ( A , B ) NEW_LINE a = math . sqrt ( a2 ) ; NEW_LINE b = math . sqrt ( b2 ) ; NEW_LINE c = math . sqrt ( c2 ) ; NEW_LINE alpha = math . acos ( ( b2 + c2 - a2 ) / ( 2 * b * c ) ) ; NEW_LINE betta = math . acos ( ( a2 + c2 - b2 ) / ( 2 * a * c ) ) ; NEW_LINE gamma = math . acos ( ( a2 + b2 - c2 ) / ( 2 * a * b ) ) ; NEW_LINE alpha = alpha * 180 / math . pi ; NEW_LINE betta = betta * 180 / math . pi ; NEW_LINE gamma = gamma * 180 / math . pi ; NEW_LINE print ( " alpha β : β % f " % ( alpha ) ) NEW_LINE print ( " betta β : β % f " % ( betta ) ) NEW_LINE print ( " gamma β : β % f " % ( gamma ) ) NEW_LINE DEDENT A = ( 0 , 0 ) NEW_LINE B = ( 0 , 1 ) NEW_LINE C = ( 1 , 0 ) NEW_LINE printAngle ( A , B , C ) ; NEW_LINE |
Triangle with no point inside | Python3 program to find triangle with no point inside ; method to get square of distance between ( x1 , y1 ) and ( x2 , y2 ) ; Method prints points which make triangle with no point inside ; any point can be chosen as first point of triangle ; choose nearest point as second point of triangle ; Get distance from first point and choose nearest one ; Pick third point by finding the second closest point with different slope . ; if already chosen point then skip them ; get distance from first point ; here cross multiplication is compared instead of division comparison ; Driver code | import sys NEW_LINE def getDistance ( x1 , y1 , x2 , y2 ) : NEW_LINE INDENT return ( x2 - x1 ) * ( x2 - x1 ) + ( y2 - y1 ) * ( y2 - y1 ) NEW_LINE DEDENT def triangleWithNoPointInside ( points , N ) : NEW_LINE INDENT first = 0 NEW_LINE second = 0 NEW_LINE third = 0 NEW_LINE minD = sys . maxsize NEW_LINE for i in range ( 0 , N ) : NEW_LINE INDENT if i == first : NEW_LINE INDENT continue NEW_LINE DEDENT d = getDistance ( points [ i ] [ 0 ] , points [ i ] [ 1 ] , points [ first ] [ 0 ] , points [ first ] [ 1 ] ) NEW_LINE if minD > d : NEW_LINE INDENT minD = d NEW_LINE second = i NEW_LINE DEDENT DEDENT minD = sys . maxsize NEW_LINE for i in range ( 0 , N ) : NEW_LINE INDENT if i == first or i == second : NEW_LINE INDENT continue NEW_LINE DEDENT d = getDistance ( points [ i ] [ 0 ] , points [ i ] [ 1 ] , points [ first ] [ 0 ] , points [ first ] [ 1 ] ) NEW_LINE if ( ( points [ i ] [ 0 ] - points [ first ] [ 0 ] ) * ( points [ second ] [ 1 ] - points [ first ] [ 1 ] ) != ( points [ second ] [ 0 ] - points [ first ] [ 0 ] ) * ( points [ i ] [ 1 ] - points [ first ] [ 1 ] ) and minD > d ) : NEW_LINE INDENT minD = d NEW_LINE third = i NEW_LINE DEDENT DEDENT print ( points [ first ] [ 0 ] , ' , β ' , points [ first ] [ 1 ] ) NEW_LINE print ( points [ second ] [ 0 ] , ' , β ' , points [ second ] [ 1 ] ) NEW_LINE print ( points [ third ] [ 0 ] , ' , β ' , points [ third ] [ 1 ] ) NEW_LINE DEDENT points = [ [ 0 , 0 ] , [ 0 , 2 ] , [ 2 , 0 ] , [ 2 , 2 ] , [ 1 , 1 ] ] NEW_LINE N = len ( points ) NEW_LINE triangleWithNoPointInside ( points , N ) NEW_LINE |
Minimum steps to minimize n as per given condition | A tabulation based solution in Python3 ; driver program | def getMinSteps ( n ) : NEW_LINE INDENT table = [ 0 ] * ( n + 1 ) NEW_LINE for i in range ( n + 1 ) : NEW_LINE INDENT table [ i ] = n - i NEW_LINE DEDENT for i in range ( n , 0 , - 1 ) : NEW_LINE INDENT if ( not ( i % 2 ) ) : NEW_LINE INDENT table [ i // 2 ] = min ( table [ i ] + 1 , table [ i // 2 ] ) NEW_LINE DEDENT if ( not ( i % 3 ) ) : NEW_LINE INDENT table [ i // 3 ] = min ( table [ i ] + 1 , table [ i // 3 ] ) NEW_LINE DEDENT DEDENT return table [ 1 ] NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT n = 14 NEW_LINE print ( getMinSteps ( n ) ) NEW_LINE DEDENT |
Minimize swaps required to make all prime | Python program for the above approach ; Create a boolean array " prime [ 0 . . n ] " and initialize all entries it as true . A value in prime [ i ] will finally be false if i is Not a prime , else true . ; If prime [ p ] is not changed , then it is a prime ; Update all multiples of p greater than or equal to the square of it numbers which are multiple of p and are less than p ^ 2 are already been marked . ; Function to count minimum number of swaps required ; To count the minimum number of swaps required to convert the array into perfectly prime ; To count total number of prime indexes in the array ; To count the total number of prime numbers in the array ; Check whether index is prime or not ; Element is not prime ; If the total number of prime numbers is greater than or equal to the total number of prime indices , then it is possible to convert the array into perfectly prime ; Driver Code ; Pre - calculate prime [ ] | import math NEW_LINE mxn = 10000 + 1 NEW_LINE prime = [ True for _ in range ( mxn + 1 ) ] NEW_LINE def SieveOfEratosthenes ( ) : NEW_LINE INDENT global prime NEW_LINE for p in range ( 2 , int ( math . sqrt ( mxn ) ) + 1 ) : NEW_LINE INDENT if ( prime [ p ] == True ) : NEW_LINE INDENT for i in range ( p * p , mxn + 1 , p ) : NEW_LINE INDENT prime [ i ] = False NEW_LINE DEDENT DEDENT DEDENT DEDENT def countMin ( arr , n ) : NEW_LINE INDENT cMinSwaps = 0 NEW_LINE cPrimeIndices = 0 NEW_LINE cPrimeNos = 0 NEW_LINE for i in range ( 0 , n ) : NEW_LINE INDENT if ( prime [ i + 1 ] ) : NEW_LINE INDENT cPrimeIndices += 1 NEW_LINE if ( not prime [ arr [ i ] ] ) : NEW_LINE INDENT cMinSwaps += 1 NEW_LINE DEDENT else : NEW_LINE INDENT cPrimeNos += 1 NEW_LINE DEDENT DEDENT elif ( prime [ arr [ i ] ] ) : NEW_LINE INDENT cPrimeNos += 1 NEW_LINE DEDENT DEDENT if ( cPrimeNos >= cPrimeIndices ) : NEW_LINE INDENT return cMinSwaps NEW_LINE DEDENT else : NEW_LINE INDENT return - 1 NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT SieveOfEratosthenes ( ) NEW_LINE n = 5 NEW_LINE arr = [ 2 , 7 , 8 , 5 , 13 ] NEW_LINE print ( countMin ( arr , n ) ) NEW_LINE DEDENT |
Find the size of Largest Subset with positive Bitwise AND | Function to find the largest possible subset having Bitwise AND positive ; Stores the number of set bits at each bit position ; Traverse the given array arr [ ] ; Current bit position ; Loop till array element becomes zero ; If the last bit is set ; Increment frequency ; Divide array element by 2 ; Decrease the bit position ; Size of the largest possible subset ; Driver Code | def largestSubset ( a , N ) : NEW_LINE INDENT bit = [ 0 for i in range ( 32 ) ] NEW_LINE for i in range ( N ) : NEW_LINE INDENT x = 31 NEW_LINE while ( a [ i ] > 0 ) : NEW_LINE INDENT if ( a [ i ] & 1 == 1 ) : NEW_LINE INDENT bit [ x ] += 1 NEW_LINE DEDENT a [ i ] = a [ i ] >> 1 NEW_LINE x -= 1 NEW_LINE DEDENT DEDENT print ( max ( bit ) ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 7 , 13 , 8 , 2 , 3 ] NEW_LINE N = len ( arr ) NEW_LINE largestSubset ( arr , N ) NEW_LINE DEDENT |
Maximum element in connected component of given node for Q queries | Function to perform the find operation to find the parent of a disjoint set ; FUnction to perform union operation of disjoint set union ; If the rank are the same ; Update the maximum value ; Function to find the maximum element of the set which belongs to the element queries [ i ] ; Stores the parent elements of the sets ; Stores the rank of the sets ; Stores the maxValue of the sets ; Update parent [ i ] and maxValue [ i ] to i ; Add arr [ i ] . first and arr [ i ] . second elements to the same set ; Find the parent element of the element queries [ i ] ; Print the maximum value of the set which belongs to the element P ; Driver Code | def Find ( parent , a ) : NEW_LINE INDENT if ( parent [ parent [ a ] ] != parent [ a ] ) : NEW_LINE INDENT parent [ a ] = findParent ( parent , parent [ a ] ) NEW_LINE DEDENT return parent [ a ] NEW_LINE DEDENT def Union ( parent , rank , maxValue , a , b ) : NEW_LINE INDENT a = Find ( parent , a ) NEW_LINE b = Find ( parent , b ) NEW_LINE if ( a == b ) : NEW_LINE INDENT return NEW_LINE DEDENT if ( rank [ a ] == rank [ b ] ) : NEW_LINE INDENT rank [ a ] += 1 NEW_LINE DEDENT if ( rank [ a ] < rank [ b ] ) : NEW_LINE INDENT temp = a NEW_LINE a = b NEW_LINE b = temp NEW_LINE DEDENT parent [ b ] = a NEW_LINE maxValue [ a ] = max ( maxValue [ a ] , maxValue [ b ] ) NEW_LINE DEDENT def findMaxValueOfSet ( arr , queries , R , N , M ) : NEW_LINE INDENT parent = [ 1 for i in range ( R + 1 ) ] NEW_LINE rank = [ 0 for i in range ( R + 1 ) ] NEW_LINE maxValue = [ 0 for i in range ( R + 1 ) ] NEW_LINE for i in range ( 1 , R + 1 , 1 ) : NEW_LINE INDENT parent [ i ] = maxValue [ i ] = i NEW_LINE DEDENT for i in range ( N ) : NEW_LINE INDENT Union ( parent , rank , maxValue , arr [ i ] [ 0 ] , arr [ i ] [ 1 ] ) NEW_LINE DEDENT for i in range ( M ) : NEW_LINE INDENT P = Find ( parent , queries [ i ] ) NEW_LINE print ( maxValue [ P ] , end = " β " ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT R = 5 NEW_LINE arr = [ [ 1 , 2 ] , [ 2 , 3 ] , [ 4 , 5 ] ] ; NEW_LINE queries = [ 2 , 4 , 1 , 3 ] NEW_LINE N = len ( arr ) NEW_LINE M = len ( queries ) NEW_LINE findMaxValueOfSet ( arr , queries , R , N , M ) NEW_LINE DEDENT |
Maximum sum of segments among all segments formed in array after Q queries | Python 3 program for the above approach ; Stores the maximum integer of the sets for each query ; Function to perform the find operation of disjoint set union ; Function to perform the Union operation of disjoint set union ; Find the parent of a and b ; Update the parent ; Update the sum of set a ; Function to find the maximum element from the sets after each operation ; Stores the rank of the sets ; Stores the sum of the sets ; Stores the maximum element for each query ; Initially set is empty ; Update the sum as the current element ; After the last query set will be empty and sum will be 0 ; Check if the current element is not in any set then make parent as current element of the queries ; Check left side of the queries [ i ] is not added in any set ; Add the queries [ i ] and the queries [ i ] - 1 in one set ; Check right side of the queries [ i ] is not added in any set ; Add queries [ i ] and the queries [ i ] + 1 in one set ; Update the maxAns ; Push maxAns to the currMax ; Print currMax values in the reverse order ; Driver Code | import sys NEW_LINE maxAns = - sys . maxsize - 1 NEW_LINE def Find ( parent , a ) : NEW_LINE INDENT if ( parent [ a ] == a ) : NEW_LINE INDENT return a NEW_LINE DEDENT return Find ( parent , parent [ a ] ) NEW_LINE DEDENT def Union ( parent , rank , setSum , a , b ) : NEW_LINE INDENT a = Find ( parent , a ) NEW_LINE b = Find ( parent , b ) NEW_LINE if ( a == b ) : NEW_LINE INDENT return NEW_LINE DEDENT if ( rank [ a ] > rank [ b ] ) : NEW_LINE INDENT rank [ a ] += 1 NEW_LINE DEDENT if ( rank [ b ] > rank [ a ] ) : NEW_LINE INDENT swap ( a , b ) NEW_LINE DEDENT parent [ b ] = a NEW_LINE setSum [ a ] += setSum [ b ] NEW_LINE DEDENT def maxValues ( arr , queries , N ) : NEW_LINE INDENT global maxAns NEW_LINE rank = [ 0 ] * ( N + 1 ) NEW_LINE setSum = [ 0 ] * ( N + 1 ) NEW_LINE currMax = [ ] NEW_LINE for i in range ( 1 , N + 1 ) : NEW_LINE INDENT parent [ i ] = - 1 NEW_LINE setSum [ i ] = arr [ i - 1 ] NEW_LINE DEDENT currMax . append ( 0 ) NEW_LINE for i in range ( N - 1 , 0 , - 1 ) : NEW_LINE INDENT if ( parent [ queries [ i ] ] == - 1 ) : NEW_LINE INDENT parent [ queries [ i ] ] = queries [ i ] NEW_LINE DEDENT if ( queries [ i ] - 1 >= 0 and parent [ queries [ i ] - 1 ] != - 1 ) : NEW_LINE INDENT Union ( parent , rank , setSum , queries [ i ] , queries [ i ] - 1 ) NEW_LINE DEDENT if ( queries [ i ] + 1 <= N and parent [ queries [ i ] + 1 ] != - 1 ) : NEW_LINE INDENT Union ( parent , rank , setSum , queries [ i ] , queries [ i ] + 1 ) NEW_LINE DEDENT maxAns = max ( setSum [ queries [ i ] ] , maxAns ) NEW_LINE currMax . append ( maxAns ) NEW_LINE DEDENT for i in range ( len ( currMax ) - 1 , - 1 , - 1 ) : NEW_LINE INDENT print ( currMax [ i ] , end = " β " ) NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 1 , 3 , 2 , 5 ] NEW_LINE queries = [ 3 , 4 , 1 , 2 ] NEW_LINE N = len ( arr ) NEW_LINE maxValues ( arr , queries , N ) NEW_LINE DEDENT |
ZigZag Level Order Traversal of an N | Structure of a tree node ; Function to create a new node ; Function to perform zig zag traversal of the given tree ; Stores the vectors containing nodes in each level of tree respectively ; Create a queue for BFS ; Enqueue Root of the tree ; Standard Level Order Traversal code using queue ; Stores the element in the current level ; Iterate over all nodes of the current level ; Insert all children of the current node into the queue ; Insert curLevel into result ; Loop to Print the ZigZag Level order Traversal of the given tree ; If i + 1 is even reverse the order of nodes in the current level ; Print the node of ith level ; Function Call | class Node : NEW_LINE INDENT def __init__ ( self , key ) : NEW_LINE INDENT self . val = key NEW_LINE self . child = [ ] NEW_LINE DEDENT DEDENT def newNode ( key ) : NEW_LINE INDENT temp = Node ( key ) NEW_LINE return temp NEW_LINE DEDENT def zigzagLevelOrder ( root ) : NEW_LINE INDENT if ( root == None ) : NEW_LINE INDENT return NEW_LINE DEDENT result = [ ] NEW_LINE q = [ ] NEW_LINE q . append ( root ) NEW_LINE while len ( q ) > 0 : NEW_LINE INDENT size = len ( q ) NEW_LINE curLevel = [ ] NEW_LINE for i in range ( size ) : NEW_LINE INDENT node = q [ 0 ] NEW_LINE q . pop ( 0 ) NEW_LINE curLevel . append ( node . val ) NEW_LINE for j in range ( len ( node . child ) ) : NEW_LINE INDENT q . append ( node . child [ j ] ) NEW_LINE DEDENT DEDENT result . append ( curLevel ) NEW_LINE DEDENT for i in range ( len ( result ) ) : NEW_LINE INDENT if ( ( i + 1 ) % 2 == 0 ) : NEW_LINE INDENT result [ i ] . reverse ( ) NEW_LINE DEDENT for j in range ( len ( result [ i ] ) ) : NEW_LINE INDENT print ( result [ i ] [ j ] , end = " β " ) NEW_LINE DEDENT print ( ) NEW_LINE DEDENT DEDENT root = newNode ( 1 ) NEW_LINE ( root . child ) . append ( newNode ( 2 ) ) NEW_LINE ( root . child ) . append ( newNode ( 3 ) ) NEW_LINE ( root . child [ 0 ] . child ) . append ( newNode ( 4 ) ) NEW_LINE ( root . child [ 0 ] . child ) . append ( newNode ( 5 ) ) NEW_LINE ( root . child [ 1 ] . child ) . append ( newNode ( 6 ) ) NEW_LINE ( root . child [ 1 ] ) . child . append ( newNode ( 7 ) ) NEW_LINE ( root . child [ 1 ] . child ) . append ( newNode ( 8 ) ) NEW_LINE zigzagLevelOrder ( root ) NEW_LINE |
Minimum length paths between 1 to N including each node | Function to calculate the distances from node 1 to N ; Vector to store our edges ; Storing the edgees in the Vector ; Initialize queue ; BFS from first node using queue ; Pop from queue ; Traversing its adjacency list ; Initialize queue ; BFS from last node using queue ; Pop from queue ; Traversing its adjacency list ; Printing the minimum distance including node i ; If not reachable ; Path exists ; Driver Code ; Given Input ; Function Call | def minDisIncludingNode ( n , m , edges ) : NEW_LINE INDENT g = [ [ ] for i in range ( 10005 ) ] NEW_LINE for i in range ( m ) : NEW_LINE INDENT a = edges [ i ] [ 0 ] - 1 NEW_LINE b = edges [ i ] [ 1 ] - 1 NEW_LINE g [ a ] . append ( b ) NEW_LINE g [ b ] . append ( a ) NEW_LINE DEDENT q = [ ] NEW_LINE q . append ( [ 0 , 0 ] ) NEW_LINE dist = [ 1e9 for i in range ( n ) ] NEW_LINE dist [ 0 ] = 0 NEW_LINE while ( len ( q ) > 0 ) : NEW_LINE INDENT up = q [ 0 ] NEW_LINE q = q [ 1 : ] NEW_LINE x = up [ 0 ] NEW_LINE lev = up [ 1 ] NEW_LINE if ( lev > dist [ x ] ) : NEW_LINE INDENT continue NEW_LINE DEDENT if ( x == n - 1 ) : NEW_LINE INDENT continue NEW_LINE DEDENT for y in g [ x ] : NEW_LINE INDENT if ( dist [ y ] > lev + 1 ) : NEW_LINE INDENT dist [ y ] = lev + 1 NEW_LINE q . append ( [ y , lev + 1 ] ) NEW_LINE DEDENT DEDENT DEDENT q1 = [ ] NEW_LINE q1 . append ( [ n - 1 , 0 ] ) NEW_LINE dist1 = [ 1e9 for i in range ( n ) ] NEW_LINE dist1 [ n - 1 ] = 0 NEW_LINE while ( len ( q1 ) > 0 ) : NEW_LINE INDENT up = q1 [ 0 ] NEW_LINE q1 = q1 [ 1 : ] NEW_LINE x = up [ 0 ] NEW_LINE lev = up [ 1 ] NEW_LINE if ( lev > dist1 [ x ] ) : NEW_LINE INDENT continue NEW_LINE DEDENT if ( x == 0 ) : NEW_LINE INDENT continue NEW_LINE DEDENT for y in g [ x ] : NEW_LINE INDENT if ( dist1 [ y ] > lev + 1 ) : NEW_LINE INDENT dist1 [ y ] = lev + 1 NEW_LINE q1 . append ( [ y , lev + 1 ] ) NEW_LINE DEDENT DEDENT DEDENT for i in range ( n ) : NEW_LINE INDENT if ( dist [ i ] + dist1 [ i ] > 1e9 ) : NEW_LINE INDENT print ( - 1 , end = " β " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( dist [ i ] + dist1 [ i ] , end = " β " ) NEW_LINE DEDENT DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT n = 5 NEW_LINE m = 7 NEW_LINE edges = [ [ 1 , 2 ] , [ 1 , 4 ] , [ 2 , 3 ] , [ 2 , 5 ] , [ 4 , 3 ] , [ 4 , 5 ] , [ 1 , 5 ] ] NEW_LINE minDisIncludingNode ( n , m , edges ) NEW_LINE DEDENT |
Check if possible to make Array sum equal to Array product by replacing exactly one element | Function to check if it is possible to form an array whose sum and the product is the same or not ; Find the sum of the array ; ; Find the product of the array ; Check a complete integer y for every x ; If got such y ; If no such y exist ; Driver Code | def canPossibleReplacement ( N , arr ) : NEW_LINE INDENT S = sum ( arr ) NEW_LINE DEDENT / * Iterate through all elements and NEW_LINE INDENT add them to sum * / NEW_LINE P = 1 NEW_LINE for i in arr : NEW_LINE INDENT P *= i NEW_LINE DEDENT for x in arr : NEW_LINE INDENT y = ( S - x ) // ( P / x - 1 ) NEW_LINE if ( S - x + y ) == ( P * y ) / x : NEW_LINE INDENT return ' Yes ' NEW_LINE DEDENT DEDENT return ' No ' NEW_LINE DEDENT N , arr = 3 , [ 1 , 3 , 4 ] NEW_LINE print ( canPossibleReplacement ( N , arr ) ) NEW_LINE |
Check if all the digits of the given number are same | Python3 program for the above approach ; Function to check if all the digits in the number N is the same or not ; Get the length of N ; Form the number M of the type K * 111. . . where K is the rightmost digit of N ; Check if the numbers are equal ; Otherwise ; Driver Code | import math NEW_LINE def checkSameDigits ( N ) : NEW_LINE INDENT length = int ( math . log10 ( N ) ) + 1 ; NEW_LINE M = ( int ( math . pow ( 10 , length ) ) - 1 ) // ( 10 - 1 ) ; NEW_LINE M *= N % 10 ; NEW_LINE if ( M == N ) : NEW_LINE INDENT return " Yes " ; NEW_LINE DEDENT return " No " ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT N = 222 ; NEW_LINE print ( checkSameDigits ( N ) ) ; NEW_LINE DEDENT |
Maximize sum of path from the Root to a Leaf node in N | Stores the maximum sum of a path ; Structure of a node in the tree ; Utility function to create a new node in the tree ; Recursive function to calculate the maximum sum in a path using DFS ; If current node is a leaf node ; Traversing all children of the current node ; Recursive call for all the children nodes ; Given Generic Tree ; Function Call | maxSumPath = 0 NEW_LINE class Node : NEW_LINE INDENT def __init__ ( self , key ) : NEW_LINE INDENT self . val = key NEW_LINE self . child = [ ] NEW_LINE DEDENT DEDENT def newNode ( key ) : NEW_LINE INDENT temp = Node ( key ) NEW_LINE return temp NEW_LINE DEDENT def DFS ( root , Sum ) : NEW_LINE INDENT global maxSumPath NEW_LINE if ( len ( root . child ) == 0 ) : NEW_LINE INDENT maxSumPath = max ( maxSumPath , Sum ) NEW_LINE return NEW_LINE DEDENT for i in range ( len ( root . child ) ) : NEW_LINE INDENT DFS ( root . child [ i ] , Sum + root . child [ i ] . val ) NEW_LINE DEDENT DEDENT root = newNode ( 1 ) NEW_LINE ( root . child ) . append ( newNode ( 2 ) ) NEW_LINE ( root . child ) . append ( newNode ( 3 ) ) NEW_LINE ( root . child [ 0 ] . child ) . append ( newNode ( 4 ) ) NEW_LINE ( root . child [ 1 ] . child ) . append ( newNode ( 6 ) ) NEW_LINE ( root . child [ 0 ] . child ) . append ( newNode ( 5 ) ) NEW_LINE ( root . child [ 1 ] ) . child . append ( newNode ( 7 ) ) NEW_LINE ( root . child [ 1 ] . child ) . append ( newNode ( 8 ) ) NEW_LINE DFS ( root , root . val ) NEW_LINE print ( maxSumPath ) NEW_LINE |
Count of even sum triplets in the array for Q range queries | Function to count number of triplets with even sum in range l , r for each query ; Initialization of array ; Initialization of variables ; Traversing array ; If element is odd ; If element is even ; Storing count of even and odd till each i ; Traversing each query ; Count of odd numbers in l to r ; Count of even numbers in l to r ; Finding the ans ; Printing the ans ; Driver Code ; Given Input ; Function Call | def countTriplets ( size , queries , arr , Q ) : NEW_LINE INDENT arr_even = [ 0 for i in range ( size + 1 ) ] NEW_LINE arr_odd = [ 0 for i in range ( size + 1 ) ] NEW_LINE even = 0 NEW_LINE odd = 0 NEW_LINE arr_even [ 0 ] = 0 NEW_LINE arr_odd [ 0 ] = 0 NEW_LINE for i in range ( size ) : NEW_LINE INDENT if ( arr [ i ] % 2 ) : NEW_LINE INDENT odd += 1 NEW_LINE DEDENT else : NEW_LINE INDENT even += 1 NEW_LINE DEDENT arr_even [ i + 1 ] = even NEW_LINE arr_odd [ i + 1 ] = odd NEW_LINE DEDENT for i in range ( queries ) : NEW_LINE INDENT l = Q [ i ] [ 0 ] NEW_LINE r = Q [ i ] [ 1 ] NEW_LINE odd = arr_odd [ r ] - arr_odd [ l - 1 ] NEW_LINE even = arr_even [ r ] - arr_even [ l - 1 ] NEW_LINE ans = ( even * ( even - 1 ) * ( even - 2 ) ) // 6 + ( odd * ( odd - 1 ) // 2 ) * even NEW_LINE print ( ans , end = " β " ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 6 NEW_LINE Q = 2 NEW_LINE arr = [ 1 , 2 , 3 , 4 , 5 , 6 ] NEW_LINE queries = [ [ 1 , 3 ] , [ 2 , 5 ] ] NEW_LINE countTriplets ( N , Q , arr , queries ) NEW_LINE DEDENT |
Maximize the rightmost element of an array in k operations in Linear Time | Function to calculate maximum value of Rightmost element ; Calculating maximum value of Rightmost element ; Checking if arr [ i ] is operationable ; Performing operation of i - th element ; Decreasing the value of k by 1 ; Printing rightmost element ; Given Input ; Function Call | def maxRightmostElement ( N , k , p , arr ) : NEW_LINE INDENT while ( k ) : NEW_LINE INDENT for i in range ( N - 2 , - 1 , - 1 ) : NEW_LINE INDENT if ( arr [ i ] >= p ) : NEW_LINE INDENT arr [ i ] = arr [ i ] - p NEW_LINE arr [ i + 1 ] = arr [ i + 1 ] + p NEW_LINE break NEW_LINE DEDENT DEDENT k = k - 1 NEW_LINE DEDENT print ( arr [ N - 1 ] ) NEW_LINE DEDENT N = 4 NEW_LINE p = 2 NEW_LINE k = 5 NEW_LINE arr = [ 3 , 8 , 1 , 4 ] NEW_LINE maxRightmostElement ( N , k , p , arr ) NEW_LINE |
Mean of minimum of all possible K | Function to find the value of nCr ; Base Case ; Find nCr recursively ; Function to find the expected minimum values of all the subsets of size K ; Find the factorials that will be used later ; Find the factorials ; Total number of subsets ; Stores the sum of minimum over all possible subsets ; Iterate over all possible minimum ; Find the mean over all subsets ; Driver Code | def nCr ( n , r , f ) : NEW_LINE INDENT if ( n < r ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT return f [ n ] / ( f [ r ] * f [ n - r ] ) NEW_LINE DEDENT def findMean ( N , X ) : NEW_LINE INDENT f = [ 0 for i in range ( N + 1 ) ] NEW_LINE f [ 0 ] = 1 NEW_LINE for i in range ( 1 , N + 1 , 1 ) : NEW_LINE INDENT f [ i ] = f [ i - 1 ] * i NEW_LINE DEDENT total = nCr ( N , X , f ) NEW_LINE count = 0 NEW_LINE for i in range ( 1 , N + 1 , 1 ) : NEW_LINE INDENT count += nCr ( N - i , X - 1 , f ) * i NEW_LINE DEDENT E_X = ( count ) / ( total ) NEW_LINE print ( " { 0 : . 9f } " . format ( E_X ) ) NEW_LINE return 0 NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 3 NEW_LINE X = 2 NEW_LINE findMean ( N , X ) NEW_LINE DEDENT |
Maximize count of odd | To find maximum number of pairs in array with conversion of at most one element ; Initialize count of even elements ; Initialize count of odd elements ; If current number is even then increment x by 1 ; If current number is odd then increment y by 1 ; Initialize the answer by min ( x , y ) ; If difference in count of odd and even is more than 2 than increment answer ; Return final answer ; Driver code ; Given array | def maximumNumberofpairs ( n , arr ) : NEW_LINE INDENT x = 0 NEW_LINE y = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( arr [ i ] % 2 == 0 ) : NEW_LINE INDENT x += 1 NEW_LINE DEDENT else : NEW_LINE INDENT y += 1 NEW_LINE DEDENT DEDENT answer = min ( x , y ) NEW_LINE if ( abs ( x - y ) >= 2 ) : NEW_LINE INDENT answer += 1 NEW_LINE DEDENT return answer NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 1 , 2 , 4 , 6 , 5 , 10 , 12 ] NEW_LINE n = len ( arr ) NEW_LINE print ( maximumNumberofpairs ( n , arr ) ) NEW_LINE DEDENT |
Sum of product of all unordered pairs in given range with update queries | Function to calculate the Pairwise Product Sum in range from L to R ; Loop to iterate over all possible pairs from L to R ; Print answer ; Function to update the Array element at index P to X ; Update the value at Pth index in the array ; Function to solve Q queries ; If Query is of type 1 ; If Query is of type 2 ; Driver Code | def pairwiseProductSum ( a , l , r ) : NEW_LINE INDENT sum = 0 NEW_LINE for j in range ( l - 1 , r , 1 ) : NEW_LINE INDENT for k in range ( j + 1 , r , 1 ) : NEW_LINE INDENT sum += ( a [ j ] * a [ k ] ) ; NEW_LINE DEDENT DEDENT print ( sum ) NEW_LINE DEDENT def updateArray ( a , p , x ) : NEW_LINE INDENT a [ p - 1 ] = x NEW_LINE DEDENT def solveQueries ( a , n , Q , query ) : NEW_LINE INDENT for i in range ( Q ) : NEW_LINE INDENT if ( query [ i ] [ 0 ] == 1 ) : NEW_LINE INDENT pairwiseProductSum ( a , query [ i ] [ 1 ] , query [ i ] [ 2 ] ) NEW_LINE DEDENT else : NEW_LINE INDENT updateArray ( a , query [ i ] [ 1 ] , query [ i ] [ 2 ] ) NEW_LINE DEDENT DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT A = [ 5 , 7 , 2 , 3 , 1 ] NEW_LINE N = len ( A ) NEW_LINE Q = 3 NEW_LINE query = [ [ 1 , 1 , 3 ] , [ 2 , 2 , 5 ] , [ 1 , 2 , 5 ] ] NEW_LINE solveQueries ( A , N , Q , query ) NEW_LINE DEDENT |
Check if final remainder is present in original Array by reducing it based on given conditions | Python program to implement above approach ; copying original array ; loop till length of array become 2. ; find middle element ; pop element from front and rear ; find remainder ; append remainder to a ; now since length of array is 2 take product and divide it by n ; if remainder is present is original array return 1 , else return 0 ; calling function Reduced ; if x = 1 print YES else NO | def Reduced ( a , n ) : NEW_LINE INDENT original_array = a [ : ] NEW_LINE while len ( a ) != 2 : NEW_LINE INDENT mid = len ( a ) // 2 NEW_LINE mid_ele = a [ mid ] NEW_LINE start = a . pop ( 0 ) NEW_LINE end = a . pop ( ) NEW_LINE rmd = ( start * end ) % mid_ele NEW_LINE a . append ( rmd ) NEW_LINE DEDENT remainder = ( a [ 0 ] * a [ 1 ] ) % n NEW_LINE if remainder in original_array : NEW_LINE INDENT return 1 NEW_LINE DEDENT return 0 NEW_LINE DEDENT Arr = [ 2 , 3 , 4 , 8 , 5 , 7 ] NEW_LINE N = len ( Arr ) NEW_LINE x = Reduced ( Arr , N ) NEW_LINE if x : NEW_LINE INDENT print ( " YES " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " NO " ) NEW_LINE DEDENT |
Find two numbers from their sum and OR | Python 3 program for the above approach ; Function to find the two integers from the given sum and Bitwise OR value ; Check if Z is non negative ; Iterate through all the bits ; Find the kth bit of A & B ; Find the kth bit of A | B ; If bit1 = 1 and bit2 = 0 , then there will be no possible pairs ; Print the possible pairs ; Driver Code | MaxBit = 32 NEW_LINE def possiblePair ( X , Y ) : NEW_LINE INDENT Z = Y - X NEW_LINE if ( Z < 0 ) : NEW_LINE INDENT print ( " - 1" ) NEW_LINE return 0 NEW_LINE DEDENT for k in range ( MaxBit ) : NEW_LINE INDENT bit1 = ( Z >> k ) & 1 NEW_LINE bit2 = ( Z >> k ) & 1 NEW_LINE if ( bit1 == 1 and bit2 == 0 ) : NEW_LINE INDENT print ( " - 1" ) NEW_LINE return 0 NEW_LINE DEDENT DEDENT print ( Z , X ) NEW_LINE return 0 NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT X = 7 NEW_LINE Y = 11 NEW_LINE possiblePair ( X , Y ) NEW_LINE DEDENT |
Maximum frequencies in each M | Function to find the frequency of the most common element in each M length subarrays ; Stores frequency of array element ; Stores the maximum frequency ; Iterate for the first sub - array and store the maximum ; Print the maximum frequency for the first subarray ; Iterate over the range [ M , N ] ; Subtract the A [ i - M ] and add the A [ i ] in the map ; Find the maximum frequency ; Print the maximum frequency for the current subarray ; Driver Code | def maxFrequencySubarrayUtil ( A , N , M ) : NEW_LINE INDENT i = 0 NEW_LINE m = { } NEW_LINE val = 0 NEW_LINE while ( i < M ) : NEW_LINE INDENT if A [ i ] in m : NEW_LINE INDENT m [ A [ i ] ] += 1 NEW_LINE DEDENT else : NEW_LINE INDENT m [ A [ i ] ] = 1 NEW_LINE DEDENT val = max ( val , m [ A [ i ] ] ) NEW_LINE i += 1 NEW_LINE DEDENT print ( val , end = " β " ) NEW_LINE for i in range ( M , N , 1 ) : NEW_LINE INDENT if A [ i - M ] in m : NEW_LINE INDENT m [ A [ i - M ] ] -= 1 NEW_LINE DEDENT else : NEW_LINE INDENT m [ A [ i - M ] ] = 0 NEW_LINE DEDENT if A [ i ] in m : NEW_LINE INDENT m [ A [ i ] ] += 1 NEW_LINE DEDENT val = 0 NEW_LINE for key , value in m . items ( ) : NEW_LINE INDENT val = max ( val , value ) NEW_LINE DEDENT print ( val , end = " β " ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT A = [ 1 , 1 , 2 , 2 , 3 , 5 ] NEW_LINE N = len ( A ) NEW_LINE M = 4 NEW_LINE maxFrequencySubarrayUtil ( A , N , M ) NEW_LINE DEDENT |
Maximum number of pairs of distinct array elements possible by including each element in only one pair | Function to count the maximum number of pairs having different element from the given array ; Stores the frequency of array element ; Stores maximum count of pairs ; Increasing the frequency of every element ; Stores the frequencies of array element from highest to lowest ; Pushing the frequencies to the priority queue ; Iterate until size of PQ > 1 ; Stores the top two element ; Form the pair between the top two pairs ; Decrement the frequencies ; Insert updated frequencies if it is greater than 0 ; Return the total count of resultant pairs ; Driver Code | def maximumPairs ( a , n ) : NEW_LINE INDENT freq = { } NEW_LINE count = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT if a [ i ] in freq : NEW_LINE INDENT freq [ a [ i ] ] += 1 NEW_LINE DEDENT else : NEW_LINE INDENT freq [ a [ i ] ] = 1 NEW_LINE DEDENT DEDENT pq = [ ] NEW_LINE for key , value in freq . items ( ) : NEW_LINE INDENT pq . append ( value ) NEW_LINE DEDENT pq . sort ( ) NEW_LINE while ( len ( pq ) > 1 ) : NEW_LINE INDENT freq1 = pq [ len ( pq ) - 1 ] NEW_LINE pq = pq [ : - 1 ] NEW_LINE freq2 = pq [ len ( pq ) - 1 ] NEW_LINE pq = pq [ : - 1 ] NEW_LINE count += 1 NEW_LINE freq1 -= 1 NEW_LINE freq2 -= 1 NEW_LINE if ( freq1 > 0 ) : NEW_LINE INDENT pq . append ( freq1 ) NEW_LINE DEDENT if ( freq2 > 0 ) : NEW_LINE INDENT pq . append ( freq2 ) NEW_LINE DEDENT pq . sort ( ) NEW_LINE DEDENT return count NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 4 , 2 , 4 , 1 , 4 , 3 ] NEW_LINE N = len ( arr ) NEW_LINE print ( maximumPairs ( arr , N ) ) NEW_LINE DEDENT |
Generate an N | Python3 program for above approach ; Function to print target array ; Sort the given array ; Seeking for index of elements with minimum diff . ; Seeking for index ; To store target array ; Copying element ; Copying remaining element ; Printing target array ; Driver Code ; Given Input ; Function Call | import sys NEW_LINE def printArr ( arr , n ) : NEW_LINE INDENT arr . sort ( ) NEW_LINE minDifference = sys . maxsize NEW_LINE minIndex = - 1 NEW_LINE for i in range ( 1 , n , 1 ) : NEW_LINE INDENT if ( minDifference > abs ( arr [ i ] - arr [ i - 1 ] ) ) : NEW_LINE INDENT minDifference = abs ( arr [ i ] - arr [ i - 1 ] ) NEW_LINE minIndex = i - 1 NEW_LINE DEDENT DEDENT Arr = [ 0 for i in range ( n ) ] NEW_LINE Arr [ 0 ] = arr [ minIndex ] NEW_LINE Arr [ n - 1 ] = arr [ minIndex + 1 ] NEW_LINE pos = 1 NEW_LINE for i in range ( minIndex + 2 , n , 1 ) : NEW_LINE INDENT Arr [ pos ] = arr [ i ] NEW_LINE pos += 1 NEW_LINE DEDENT for i in range ( minIndex ) : NEW_LINE INDENT Arr [ pos ] = arr [ i ] NEW_LINE pos += 1 NEW_LINE DEDENT for i in range ( n ) : NEW_LINE INDENT print ( Arr [ i ] , end = " β " ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 8 NEW_LINE arr = [ 4 , 6 , 2 , 6 , 8 , 2 , 6 , 4 ] NEW_LINE printArr ( arr , N ) NEW_LINE DEDENT |
Construct a Perfect Binary Tree from Preorder Traversal | Structure of the tree ; Function to create a new node with the value val ; Return the newly created node ; Function to create the Perfect Binary Tree ; If preStart > preEnd return NULL ; Initialize root as pre [ preStart ] ; If the only node is left , then return node ; Parameters for further recursion ; Recursive Call to build the subtree of root node ; Return the created root ; Function to build Perfect Binary Tree ; Function to print the Inorder of the given Tree ; Base Case ; Left Recursive Call ; Print the data ; Right Recursive Call ; Driver Code ; Function Call ; Print Inorder Traversal | class Node : NEW_LINE INDENT def __init__ ( self , val ) : NEW_LINE INDENT self . data = val NEW_LINE self . left = None NEW_LINE self . right = None NEW_LINE DEDENT DEDENT def getNewNode ( val ) : NEW_LINE INDENT newNode = Node ( val ) NEW_LINE return newNode NEW_LINE DEDENT def buildPerfectBT_helper ( preStart , preEnd , pre ) : NEW_LINE INDENT if ( preStart > preEnd ) : NEW_LINE INDENT return None NEW_LINE DEDENT root = getNewNode ( pre [ preStart ] ) NEW_LINE if ( preStart == preEnd ) : NEW_LINE INDENT return root NEW_LINE DEDENT leftPreStart = preStart + 1 NEW_LINE rightPreStart = leftPreStart + int ( ( preEnd - leftPreStart + 1 ) / 2 ) NEW_LINE leftPreEnd = rightPreStart - 1 NEW_LINE rightPreEnd = preEnd NEW_LINE root . left = buildPerfectBT_helper ( leftPreStart , leftPreEnd , pre ) NEW_LINE root . right = buildPerfectBT_helper ( rightPreStart , rightPreEnd , pre ) NEW_LINE return root NEW_LINE DEDENT def buildPerfectBT ( pre , size ) : NEW_LINE INDENT return buildPerfectBT_helper ( 0 , size - 1 , pre ) NEW_LINE DEDENT def printInorder ( root ) : NEW_LINE INDENT if ( root == None ) : NEW_LINE INDENT return NEW_LINE DEDENT printInorder ( root . left ) NEW_LINE print ( root . data , " " , end = " " ) NEW_LINE printInorder ( root . right ) NEW_LINE DEDENT pre = [ 1 , 2 , 4 , 5 , 3 , 6 , 7 ] NEW_LINE N = len ( pre ) NEW_LINE root = buildPerfectBT ( pre , N ) NEW_LINE print ( " Inorder β traversal β of β the β tree : β " , end = " " ) NEW_LINE printInorder ( root ) NEW_LINE |
Minimize operations to convert each node of N | Create adjacency list ; Function to add an edges in graph ; Function to perform the DFS of graph recursively from a given vertex u ; Check for the condition for the flipping of node 's initial value ; Traverse all the children of the current source node u ; Swap foo and foo1 signifies there is change of level ; Function to perform the DFSUtil ( ) for all the unvisited vertices ; Traverse the given set of nodes ; If the current node is unvisited ; Print the number of operations ; Function to count the number of flips required to change initial node values to final node value ; Add the given edges ; DFS Traversal ; Driver code | N = 3 NEW_LINE adj = [ ] NEW_LINE for i in range ( N + 1 ) : NEW_LINE INDENT adj . append ( [ ] ) NEW_LINE DEDENT visited = [ ] NEW_LINE ans = 0 NEW_LINE def addEdges ( u , v ) : NEW_LINE INDENT global adj NEW_LINE adj [ u ] . append ( v ) NEW_LINE adj [ v ] . append ( u ) NEW_LINE DEDENT def DFSUtil ( u , foo , foo1 , initial , finall ) : NEW_LINE INDENT global visited , ans , adj NEW_LINE visited [ u ] = True NEW_LINE if ( ( initial [ u - 1 ] ^ foo ) ^ finall [ u - 1 ] == True ) : NEW_LINE INDENT ans += 1 NEW_LINE foo ^= True NEW_LINE DEDENT for i in range ( len ( adj [ u ] ) ) : NEW_LINE INDENT if ( visited [ adj [ u ] [ i ] ] == False ) : NEW_LINE INDENT DFSUtil ( adj [ u ] [ i ] , foo1 , foo , initial , finall ) NEW_LINE DEDENT DEDENT DEDENT def DFS ( V , initial , finall ) : NEW_LINE INDENT global ans , visited NEW_LINE ans = 0 NEW_LINE visited = [ False ] * V NEW_LINE for u in range ( 1 , 2 ) : NEW_LINE INDENT if ( visited [ u ] == False ) : NEW_LINE INDENT DFSUtil ( u , 0 , 0 , initial , finall ) NEW_LINE DEDENT DEDENT print ( ans ) NEW_LINE DEDENT def countOperations ( N , initial , finall , Edges ) : NEW_LINE INDENT for i in range ( N - 1 ) : NEW_LINE INDENT addEdges ( Edges [ i ] [ 0 ] , Edges [ i ] [ 1 ] ) NEW_LINE DEDENT DFS ( N + 1 , initial , finall ) NEW_LINE DEDENT Edges = [ [ 1 , 2 ] , [ 1 , 3 ] ] NEW_LINE initial = [ True , True , False ] NEW_LINE finall = [ False , True , True ] NEW_LINE countOperations ( N , initial , finall , Edges ) NEW_LINE |
Minimum number of moves to make M and N equal by repeatedly adding any divisor of number to itself except 1 and the number | Function to find the minimum number of moves to make N and M equal . ; Array to maintain the numbers included . ; Pair of vertex , count ; Run bfs from N ; If we reached goal ; Iterate in the range ; If i is a factor of aux ; If i is less than M - aux and is not included earlier . ; If aux / i is less than M - aux and is not included earlier . ; Not possible ; Driver code | def countOperations ( N , M ) : NEW_LINE INDENT visited = [ False ] * ( 100001 ) NEW_LINE Q = [ ] NEW_LINE Q . append ( [ N , 0 ] ) NEW_LINE visited [ N ] = True NEW_LINE while ( len ( Q ) > 0 ) : NEW_LINE INDENT aux = Q [ 0 ] [ 0 ] NEW_LINE cont = Q [ 0 ] [ 1 ] NEW_LINE Q . pop ( 0 ) NEW_LINE if ( aux == M ) : NEW_LINE INDENT return cont NEW_LINE DEDENT i = 2 NEW_LINE while i * i <= aux : NEW_LINE INDENT if ( aux % i == 0 ) : NEW_LINE INDENT if ( aux + i <= M and not visited [ aux + i ] ) : NEW_LINE INDENT Q . append ( [ aux + i , cont + 1 ] ) NEW_LINE visited [ aux + i ] = True NEW_LINE DEDENT if ( aux + int ( aux / i ) <= M and not visited [ aux + int ( aux / i ) ] ) : NEW_LINE INDENT Q . append ( [ aux + int ( aux / i ) , cont + 1 ] ) NEW_LINE visited [ aux + int ( aux / i ) ] = True NEW_LINE DEDENT DEDENT i += 1 NEW_LINE DEDENT DEDENT return - 1 NEW_LINE DEDENT N , M = 4 , 24 NEW_LINE print ( countOperations ( N , M ) ) NEW_LINE |
Finding Astronauts from different countries | Function to perform the DFS Traversal to find the count of connected components ; Marking vertex visited ; DFS call to neighbour vertices ; If the current node is not visited , then recursively call DFS ; Function to find the number of ways to choose two astronauts from the different countries ; Stores the Adjacency list ; Constructing the graph ; Stores the visited vertices ; Stores the size of every connected components ; DFS call to the graph ; Store size of every connected component ; Stores the total number of ways to count the pairs ; Traverse the array ; Print the value of ans ; Driver Code | adj = [ ] NEW_LINE visited = [ ] NEW_LINE num = 0 NEW_LINE def dfs ( v ) : NEW_LINE INDENT global adj , visited , num NEW_LINE visited [ v ] = True NEW_LINE num += 1 NEW_LINE for i in range ( len ( adj [ v ] ) ) : NEW_LINE INDENT if ( not visited [ adj [ v ] [ i ] ] ) : NEW_LINE INDENT dfs ( adj [ v ] [ i ] ) NEW_LINE DEDENT DEDENT DEDENT def numberOfPairs ( N , arr ) : NEW_LINE INDENT global adj , visited , num NEW_LINE adj = [ ] NEW_LINE for i in range ( N ) : NEW_LINE INDENT adj . append ( [ ] ) NEW_LINE DEDENT for i in range ( len ( arr ) ) : NEW_LINE INDENT adj [ arr [ i ] [ 0 ] ] . append ( arr [ i ] [ 1 ] ) NEW_LINE adj [ arr [ i ] [ 1 ] ] . append ( arr [ i ] [ 0 ] ) NEW_LINE DEDENT visited = [ False ] * ( N ) NEW_LINE v = [ ] NEW_LINE num = 0 NEW_LINE for i in range ( N ) : NEW_LINE INDENT if ( not visited [ i ] ) : NEW_LINE INDENT dfs ( i ) NEW_LINE v . append ( num ) NEW_LINE num = 0 NEW_LINE DEDENT DEDENT ans = N * int ( ( N - 1 ) / 2 ) NEW_LINE for i in range ( len ( v ) ) : NEW_LINE INDENT ans -= ( v [ i ] * int ( ( v [ i ] - 1 ) / 2 ) ) NEW_LINE DEDENT ans += 1 NEW_LINE print ( ans ) NEW_LINE DEDENT N = 6 NEW_LINE arr = [ [ 0 , 1 ] , [ 0 , 2 ] , [ 2 , 5 ] ] NEW_LINE numberOfPairs ( N , arr ) NEW_LINE |
Count of Perfect Numbers in given range for Q queries | python 3 program for the above approach ; Function to check whether a number is perfect Number ; Stores sum of divisors ; Itearate over the range [ 2 , sqrt ( N ) ] ; If sum of divisors is equal to N , then N is a perfect number ; Function to find count of perfect numbers in a given range ; Stores the count of perfect Numbers upto a every number less than MAX ; Iterate over the range [ 1 , MAX ] ; Traverse the array arr [ ] ; Print the count of perfect numbers in the range [ arr [ i ] [ 0 ] , arr [ i ] [ 1 ] ] ; Driver Code | MAX = 100005 NEW_LINE from math import sqrt NEW_LINE def isPerfect ( N ) : NEW_LINE INDENT sum = 1 NEW_LINE for i in range ( 2 , int ( sqrt ( N ) ) + 1 , 1 ) : NEW_LINE INDENT if ( N % i == 0 ) : NEW_LINE INDENT if ( i * i != N ) : NEW_LINE INDENT sum = sum + i + N // i NEW_LINE DEDENT else : NEW_LINE INDENT sum = sum + i NEW_LINE DEDENT DEDENT DEDENT if ( sum == N and N != 1 ) : NEW_LINE INDENT return True NEW_LINE DEDENT return False NEW_LINE DEDENT def Query ( arr , N ) : NEW_LINE INDENT prefix = [ 0 for i in range ( MAX + 1 ) ] NEW_LINE for i in range ( 2 , MAX + 1 , 1 ) : NEW_LINE INDENT prefix [ i ] = prefix [ i - 1 ] + isPerfect ( i ) NEW_LINE DEDENT for i in range ( N ) : NEW_LINE INDENT print ( prefix [ arr [ i ] [ 1 ] ] - prefix [ arr [ i ] [ 0 ] - 1 ] , end = " β " ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ [ 1 , 1000 ] , [ 1000 , 2000 ] , [ 2000 , 3000 ] ] NEW_LINE N = len ( arr ) NEW_LINE Query ( arr , N ) NEW_LINE DEDENT |
Find any possible two coordinates of Rectangle whose two coordinates are given | Function to find the remaining two rectangle coordinates ; Pairs to store the position of given two coordinates of the rectangle . ; Pairs to store the remaining two coordinates of the rectangle . ; Traverse through matrix and find pairs p1 and p2 ; First Case ; Second Case ; Third Case ; Print the matrix ; Driver code ; Given Input ; Function Call | def Create_Rectangle ( arr , n ) : NEW_LINE INDENT for i in range ( n ) : NEW_LINE INDENT arr [ i ] = [ i for i in arr [ i ] ] NEW_LINE DEDENT p1 = [ - 1 , - 1 ] NEW_LINE p2 = [ - 1 , - 1 ] NEW_LINE p3 = [ ] NEW_LINE p4 = [ ] NEW_LINE for i in range ( n ) : NEW_LINE INDENT for j in range ( n ) : NEW_LINE INDENT if ( arr [ i ] [ j ] == '1' ) : NEW_LINE INDENT if ( p1 [ 0 ] == - 1 ) : NEW_LINE INDENT p1 = [ i , j ] NEW_LINE DEDENT else : NEW_LINE INDENT p2 = [ i , j ] NEW_LINE DEDENT DEDENT DEDENT DEDENT p3 = p1 NEW_LINE p4 = p2 NEW_LINE if ( p1 [ 0 ] == p2 [ 0 ] ) : NEW_LINE INDENT p3 [ 0 ] = ( p1 [ 0 ] + 1 ) % n NEW_LINE p4 [ 0 ] = ( p2 [ 0 ] + 1 ) % n NEW_LINE DEDENT elif ( p1 [ 1 ] == p2 [ 1 ] ) : NEW_LINE INDENT p3 [ 1 ] = ( p1 [ 1 ] + 1 ) % n NEW_LINE p4 [ 1 ] = ( p2 [ 1 ] + 1 ) % n NEW_LINE DEDENT else : NEW_LINE INDENT p3 [ 0 ] , p4 [ 0 ] = p4 [ 0 ] , p3 [ 0 ] NEW_LINE DEDENT arr [ p3 [ 0 ] ] [ p3 [ 1 ] ] = '1' NEW_LINE arr [ p4 [ 0 ] ] [ p4 [ 1 ] ] = '1' NEW_LINE for i in range ( n ) : NEW_LINE INDENT print ( " " . join ( arr [ i ] ) ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT n = 4 NEW_LINE arr = [ "0010" , "0000" , "1000" , "0000" ] NEW_LINE Create_Rectangle ( arr , n ) NEW_LINE DEDENT |
Sum of all the prime divisors of a number | Set 2 | Python3 program for the above approach ; Function to find sum of prime divisors of the given number N ; Add the number 2 if it divides N ; Traverse the loop from [ 3 , sqrt ( N ) ] ; If i divides N , add i and divide N ; This condition is to handle the case when N is a prime number greater than 2 ; Driver code ; Given input ; Function call | import math NEW_LINE def SumOfPrimeDivisors ( n ) : NEW_LINE INDENT sum = 0 NEW_LINE if n % 2 == 0 : NEW_LINE INDENT sum += 2 NEW_LINE DEDENT while n % 2 == 0 : NEW_LINE INDENT n //= 2 NEW_LINE DEDENT k = int ( math . sqrt ( n ) ) NEW_LINE for i in range ( 3 , k + 1 , 2 ) : NEW_LINE INDENT if n % i == 0 : NEW_LINE INDENT sum += i NEW_LINE DEDENT while n % i == 0 : NEW_LINE INDENT n //= i NEW_LINE DEDENT DEDENT if n > 2 : NEW_LINE INDENT sum += n NEW_LINE DEDENT return sum NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT n = 10 NEW_LINE print ( SumOfPrimeDivisors ( n ) ) NEW_LINE DEDENT |
Minimum insertions to form a palindrome | DP | A Naive recursive program to find minimum number insertions needed to make a string palindrome ; Recursive function to find minimum number of insertions ; Base Cases ; Check if the first and last characters are same . On the basis of the comparison result , decide which subrpoblem ( s ) to call ; Driver Code | import sys NEW_LINE def findMinInsertions ( str , l , h ) : NEW_LINE INDENT if ( l > h ) : NEW_LINE INDENT return sys . maxsize NEW_LINE DEDENT if ( l == h ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT if ( l == h - 1 ) : NEW_LINE INDENT return 0 if ( str [ l ] == str [ h ] ) else 1 NEW_LINE DEDENT if ( str [ l ] == str [ h ] ) : NEW_LINE INDENT return findMinInsertions ( str , l + 1 , h - 1 ) NEW_LINE DEDENT else : NEW_LINE INDENT return ( min ( findMinInsertions ( str , l , h - 1 ) , findMinInsertions ( str , l + 1 , h ) ) + 1 ) NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT str = " geeks " NEW_LINE print ( findMinInsertions ( str , 0 , len ( str ) - 1 ) ) NEW_LINE DEDENT |
Count bases which contains a set bit as the Most Significant Bit in the representation of N | Python 3 program for the above approach ; Function to count bases having MSB of N as a set bit ; Store the required count ; Iterate over the range [ 2 , N ] ; Store the MSB of N ; If MSB is 1 , then increment the count by 1 ; Return the count ; Driver Code | import math NEW_LINE def countOfBase ( N ) : NEW_LINE INDENT count = 0 NEW_LINE for i in range ( 2 , N + 1 ) : NEW_LINE INDENT highestPower = int ( math . log ( N ) / math . log ( i ) ) NEW_LINE firstDigit = int ( N / int ( math . pow ( i , highestPower ) ) ) NEW_LINE if ( firstDigit == 1 ) : NEW_LINE INDENT count += 1 NEW_LINE DEDENT DEDENT return count NEW_LINE DEDENT N = 6 NEW_LINE print ( countOfBase ( N ) ) NEW_LINE |
K | Function to find the kth digit from last in an integer n ; If k is less than equal to 0 ; Convert integer into string ; If k is greater than length of the temp ; Print the k digit from last ; Driver code ; Given Input ; Function call | def kthDigitFromLast ( n , k ) : NEW_LINE INDENT if ( k <= 0 ) : NEW_LINE INDENT print ( - 1 ) NEW_LINE return NEW_LINE DEDENT temp = str ( n ) NEW_LINE if ( k > len ( temp ) ) : NEW_LINE INDENT print ( - 1 ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( ord ( temp [ len ( temp ) - k ] ) - ord ( '0' ) ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT n = 2354 NEW_LINE k = 2 NEW_LINE kthDigitFromLast ( n , k ) NEW_LINE DEDENT |
Count ways to split array into three non | Function to count ways to split array into three subarrays with equal Bitwise XOR ; Stores the XOR value of arr [ ] ; Update the value of arr_xor ; Stores the XOR value of prefix and suffix array respectively ; Stores the ending points of all the required prefix arrays ; Stores the count of suffix arrays whose XOR value is equal to the total XOR value at each index ; Find all prefix arrays with XOR value equal to arr_xor ; Update pref_xor ; Fill the values of suff_inds [ ] ; Update suff_xor ; Update suff_inds [ i ] ; Stores the total number of ways ; Count total number of ways ; Return the final count ; Driver Code ; Given Input ; Function Call | def countWays ( arr , N ) : NEW_LINE INDENT arr_xor = 0 NEW_LINE for i in range ( N ) : NEW_LINE INDENT arr_xor ^= arr [ i ] NEW_LINE DEDENT pref_xor , suff_xor = 0 , 0 NEW_LINE pref_ind = [ ] NEW_LINE suff_inds = [ 0 ] * ( N + 1 ) NEW_LINE for i in range ( N ) : NEW_LINE INDENT pref_xor ^= arr [ i ] NEW_LINE if ( pref_xor == arr_xor ) : NEW_LINE INDENT pref_ind . append ( i ) NEW_LINE DEDENT DEDENT for i in range ( N - 1 , - 1 , - 1 ) : NEW_LINE INDENT suff_xor ^= arr [ i ] NEW_LINE suff_inds [ i ] += suff_inds [ i + 1 ] NEW_LINE if ( suff_xor == arr_xor ) : NEW_LINE INDENT suff_inds [ i ] += 1 NEW_LINE DEDENT DEDENT tot_ways = 0 NEW_LINE for idx in pref_ind : NEW_LINE INDENT if ( idx < N - 1 ) : NEW_LINE INDENT tot_ways += suff_inds [ idx + 2 ] NEW_LINE DEDENT DEDENT return tot_ways NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 7 , 0 , 5 , 2 , 7 ] NEW_LINE N = len ( arr ) NEW_LINE print ( countWays ( arr , N ) ) NEW_LINE DEDENT |
Count pairs up to N having sum equal to their XOR | 2D array for memoization ; Recursive Function to count pairs ( x , y ) such that x + y = x ^ y ; If the string is traversed completely ; If the current subproblem is already calculated ; If bound = 1 and s [ i ] = = '0' , only ( 0 , 0 ) can be placed ; Otherwise ; Placing ( 0 , 1 ) and ( 1 , 0 ) are equivalent . Hence , multiply by 2. ; Place ( 0 , 0 ) at the current position . ; Return the answer ; Utility Function to convert N to its binary representation ; Function to count pairs ( x , y ) such that x + y = x ^ y ; Convert the number to equivalent binary representation ; Print answer returned by recursive function ; Driver code ; Input ; Function call | dp = [ [ - 1 for i in range ( 2 ) ] for j in range ( 1000 ) ] NEW_LINE def IsSumEqualsXor ( i , n , bound , s ) : NEW_LINE INDENT if ( i == n ) : NEW_LINE INDENT return 1 NEW_LINE DEDENT if ( dp [ i ] [ bound ] != - 1 ) : NEW_LINE INDENT return dp [ i ] [ bound ] NEW_LINE DEDENT ans = 0 NEW_LINE if ( bound and s [ i ] == '0' ) : NEW_LINE INDENT ans = IsSumEqualsXor ( i + 1 , n , 1 , s ) NEW_LINE DEDENT else : NEW_LINE INDENT ans = 2 * IsSumEqualsXor ( i + 1 , n , bound & ( s [ i ] == '1' ) , s ) NEW_LINE ans += IsSumEqualsXor ( i + 1 , n , 0 , s ) NEW_LINE DEDENT dp [ i ] [ bound ] = ans NEW_LINE return ans NEW_LINE DEDENT def convertToBinary ( n ) : NEW_LINE INDENT ans = [ ] NEW_LINE while ( n ) : NEW_LINE INDENT rem = chr ( n % 2 + 48 ) NEW_LINE ans . append ( rem ) NEW_LINE n //= 2 NEW_LINE DEDENT ans = ans [ : : - 1 ] NEW_LINE return ans NEW_LINE DEDENT def IsSumEqualsXorUtil ( N ) : NEW_LINE INDENT s = convertToBinary ( N ) NEW_LINE print ( IsSumEqualsXor ( 0 , len ( s ) , 1 , s ) ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 10 NEW_LINE IsSumEqualsXorUtil ( N ) NEW_LINE DEDENT |
Mean of fourth powers of first N natural numbers | Function to find the average of the fourth power of first N natural numbers ; Stores the sum of the fourth powers of first N natural numbers ; Calculate the sum of fourth power ; Return the average ; Driver Code | def findAverage ( N ) : NEW_LINE INDENT S = 0 NEW_LINE for i in range ( 1 , N + 1 ) : NEW_LINE INDENT S += i * i * i * i NEW_LINE DEDENT return round ( S / N , 4 ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 3 NEW_LINE print ( findAverage ( N ) ) NEW_LINE DEDENT |
Construct a graph from given degrees of all vertices | A function to print the adjacency matrix . ; n is number of vertices ; For each pair of vertex decrement the degree of both vertex . ; Print the result in specified form ; Driver Code | def printMat ( degseq , n ) : NEW_LINE INDENT mat = [ [ 0 ] * n for i in range ( n ) ] NEW_LINE for i in range ( n ) : NEW_LINE INDENT for j in range ( i + 1 , n ) : NEW_LINE INDENT if ( degseq [ i ] > 0 and degseq [ j ] > 0 ) : NEW_LINE INDENT degseq [ i ] -= 1 NEW_LINE degseq [ j ] -= 1 NEW_LINE mat [ i ] [ j ] = 1 NEW_LINE mat [ j ] [ i ] = 1 NEW_LINE DEDENT DEDENT DEDENT print ( " β " , end = " β " ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT print ( " β " , " ( " , i , " ) " , end = " " ) NEW_LINE DEDENT print ( ) NEW_LINE print ( ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT print ( " β " , " ( " , i , " ) " , end = " " ) NEW_LINE for j in range ( n ) : NEW_LINE INDENT print ( " β " , mat [ i ] [ j ] , end = " " ) NEW_LINE DEDENT print ( ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT degseq = [ 2 , 2 , 1 , 1 , 1 ] NEW_LINE n = len ( degseq ) NEW_LINE printMat ( degseq , n ) NEW_LINE DEDENT |
Decimal equivalent of concatenation of absolute difference of floor and rounded | Function to find the decimal equivalent of the new binary array constructed from absolute decimal of floor and the round - off values ; Traverse the givenarray from the end ; Stores the absolute difference between floor and round - off each array element ; If bit / difference is 1 , then calculate the bit by proper power of 2 and add it to result ; Increment the value of power ; Print the result ; Driver Code | def findDecimal ( arr , N ) : NEW_LINE INDENT power = 0 ; NEW_LINE result = 0 ; NEW_LINE for i in range ( N - 1 , - 1 , - 1 ) : NEW_LINE INDENT bit = abs ( int ( arr [ i ] ) - round ( arr [ i ] ) ) ; NEW_LINE if ( bit ) : NEW_LINE INDENT result += pow ( 2 , power ) ; NEW_LINE DEDENT power += 1 ; NEW_LINE DEDENT print ( result ) ; NEW_LINE DEDENT arr = [ 1.2 , 2.6 , 4.2 , 6.9 , 3.1 , 21.6 , 91.2 ] ; NEW_LINE N = len ( arr ) NEW_LINE findDecimal ( arr , N ) ; NEW_LINE |
Calculate money placed in boxes after N days based on given conditions | Function to find the total money placed in boxes after N days ; Stores the total money ; Iterate for N days ; Adding the Week number ; Adding previous amount + 1 ; Return the total amount ; Input ; Function call to find total money placed | def totalMoney ( N ) : NEW_LINE INDENT ans = 0 NEW_LINE for i in range ( 0 , N ) : NEW_LINE INDENT ans += i / 7 NEW_LINE ans += ( i % 7 + 1 ) NEW_LINE DEDENT return ans NEW_LINE DEDENT N = 15 NEW_LINE print ( totalMoney ( N ) ) NEW_LINE |
Sum of absolute differences of indices of occurrences of each array element | Set 2 | Stores the count of occurrences and previous index of every element ; Constructor ; Function to calculate the sum of absolute differences of indices of occurrences of array element ; Stores the count of elements and their previous indices ; Initialize 2 arrays left [ ] and right [ ] of size N ; Traverse the given array ; If arr [ i ] is present in the Map ; Update left [ i ] to 0 and update the value of arr [ i ] in map ; Otherwise , get the value from the map and update left [ i ] ; Clear the map to calculate right [ ] array ; Traverse the array arr [ ] in reverse ; If arr [ i ] is present in theMap ; Update right [ i ] to 0 and update the value of arr [ i ] in the Map ; Otherwise get the value from the map and update right [ i ] ; Iterate in the range [ 0 , N - 1 ] and print the sum of left [ i ] and right [ i ] as the result ; Driver Code | class pair : NEW_LINE INDENT def __init__ ( self , count , prevIndex ) : NEW_LINE INDENT self . count = count ; NEW_LINE self . prevIndex = prevIndex ; NEW_LINE DEDENT DEDENT def findSum ( arr , n ) : NEW_LINE INDENT map = { } ; NEW_LINE left = [ 0 for i in range ( n ) ] ; NEW_LINE right = [ 0 for i in range ( n ) ] ; NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( arr [ i ] not in map ) : NEW_LINE INDENT left [ i ] = 0 ; NEW_LINE map [ arr [ i ] ] = pair ( 1 , i ) ; NEW_LINE DEDENT else : NEW_LINE INDENT tmp = map [ arr [ i ] ] ; NEW_LINE left [ i ] = ( tmp . count ) * ( i - tmp . prevIndex ) + left [ tmp . prevIndex ] NEW_LINE map [ arr [ i ] ] = pair ( tmp . count + 1 , i ) ; NEW_LINE DEDENT DEDENT map . clear ( ) ; NEW_LINE for i in range ( n - 1 , - 1 , - 1 ) : NEW_LINE INDENT if ( arr [ i ] not in map ) : NEW_LINE INDENT right [ i ] = 0 ; NEW_LINE map [ arr [ i ] ] = pair ( 1 , i ) ; NEW_LINE DEDENT else : NEW_LINE INDENT tmp = map [ arr [ i ] ] ; NEW_LINE right [ i ] = ( tmp . count ) * ( abs ( i - tmp . prevIndex ) ) + right [ tmp . prevIndex ] ; NEW_LINE map [ arr [ i ] ] = pair ( tmp . count + 1 , i ) ; NEW_LINE DEDENT DEDENT for i in range ( n ) : NEW_LINE INDENT print ( left [ i ] + right [ i ] , end = " β " ) ; NEW_LINE DEDENT DEDENT arr = [ 1 , 3 , 1 , 1 , 2 ] ; NEW_LINE N = len ( arr ) ; NEW_LINE findSum ( arr , N ) ; NEW_LINE |
Convert a number to another by dividing by its factor or removing first occurrence of a digit from an array | Python3 program for the above approach ; Function to check if a digit x is present in the number N or not ; Convert N to string ; Traverse the num ; Return first occurrence of the digit x ; Function to remove the character at a given index from the number ; Convert N to string ; Store the resultant string ; Traverse the num ; If the number becomes empty after deletion , then return - 1 ; Return the number ; Function to check if A can be reduced to B by performing the operations any number of times ; Create a queue ; Push A into the queue ; Hashmap to check if the element is present in the Queue or not ; Set A as visited ; Iterate while the queue is not empty ; Store the front value of the queue and pop it from it ; If top is equal to B , then return true ; Traverse the array , D [ ] ; Divide top by D [ i ] if it is possible and push the result in q ; If D [ i ] is present at the top ; Remove the first occurrence of D [ i ] from the top and store the new number ; Push newElement into the queue q ; Return false if A can not be reduced to B ; Driver Code | from collections import deque NEW_LINE def isPresent ( n , x ) : NEW_LINE INDENT num = str ( n ) NEW_LINE for i in range ( len ( num ) ) : NEW_LINE INDENT if ( ( ord ( num [ i ] ) - ord ( '0' ) ) == x ) : NEW_LINE INDENT return i NEW_LINE DEDENT DEDENT return - 1 NEW_LINE DEDENT def removeDigit ( n , index ) : NEW_LINE INDENT num = str ( n ) NEW_LINE ans = " " NEW_LINE for i in range ( len ( num ) ) : NEW_LINE INDENT if ( i != index ) : NEW_LINE INDENT ans += num [ i ] NEW_LINE DEDENT DEDENT if ( ans == " " or ( len ( ans ) == 1 and ans [ 0 ] == '0' ) ) : NEW_LINE INDENT return - 1 NEW_LINE DEDENT x = int ( ans ) NEW_LINE return x NEW_LINE DEDENT def reduceNtoX ( a , b , d , n ) : NEW_LINE INDENT q = deque ( ) NEW_LINE q . append ( a ) NEW_LINE visited = { } NEW_LINE visited [ a ] = True NEW_LINE while ( len ( q ) > 0 ) : NEW_LINE INDENT top = q . popleft ( ) NEW_LINE if ( top < 0 ) : NEW_LINE INDENT continue NEW_LINE DEDENT if ( top == b ) : NEW_LINE INDENT return True NEW_LINE DEDENT for i in range ( n ) : NEW_LINE INDENT if ( d [ i ] != 0 and top % d [ i ] == 0 and ( top // d [ i ] not in visited ) ) : NEW_LINE INDENT q . append ( top // d [ i ] ) NEW_LINE visited [ top // d [ i ] ] = True NEW_LINE DEDENT index = isPresent ( top , d [ i ] ) NEW_LINE if ( index != - 1 ) : NEW_LINE INDENT newElement = removeDigit ( top , index ) NEW_LINE if ( newElement != - 1 and ( newElement not in visited ) ) : NEW_LINE INDENT q . append ( newElement ) NEW_LINE visited [ newElement ] = True NEW_LINE DEDENT DEDENT DEDENT DEDENT return False NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT A , B = 5643 , 81 NEW_LINE D = [ 3 , 8 , 1 ] NEW_LINE N = len ( D ) NEW_LINE if ( reduceNtoX ( A , B , D , N ) ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT DEDENT |
Prime triplets consisting of values up to N having difference between two elements equal to the third | Python3 program for the above approach ; Stores 1 and 0 at indices which are prime and non - prime respectively ; Function to find all prime numbers from the range [ 0 , N ] ; Iterate over the range [ 2 , sqrt ( N ) ] ; If p is a prime ; Update all tultiples of p as false ; Function to find all prime triplets satisfying the given conditions ; Generate all primes up to N ; ; Iterate over the range [ 3 , N ] ; Check for the condition ; Store the triplets ; Print all the stored triplets ; Driver Code | from math import sqrt NEW_LINE prime = [ True for i in range ( 100000 ) ] NEW_LINE def SieveOfEratosthenes ( n ) : NEW_LINE INDENT for p in range ( 2 , int ( sqrt ( n ) ) + 1 , 1 ) : NEW_LINE INDENT if ( prime [ p ] == True ) : NEW_LINE INDENT for i in range ( p * p , n + 1 , p ) : NEW_LINE INDENT prime [ i ] = False NEW_LINE DEDENT DEDENT DEDENT DEDENT def findTriplets ( N ) : NEW_LINE INDENT SieveOfEratosthenes ( N ) NEW_LINE DEDENT / * List < List < int > > V = new List < List < int >> ( ) ; * / NEW_LINE INDENT for i in range ( 3 , N + 1 , 1 ) : NEW_LINE INDENT if ( 2 + i <= N and prime [ i ] and prime [ 2 + i ] ) : NEW_LINE INDENT V . append ( [ 2 , i , i + 2 ] ) NEW_LINE DEDENT DEDENT for i in range ( len ( V ) ) : NEW_LINE INDENT print ( V [ i ] [ 0 ] , V [ i ] [ 1 ] , V [ i ] [ 2 ] ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 8 NEW_LINE findTriplets ( N ) NEW_LINE DEDENT |
Smallest number which is not coprime with any element of an array | Python 3 program for the above approach ; Function check if a number is prime or not ; Corner cases ; Check if n is divisible by 2 or 3 ; Check for every 6 th number . The above checking allows to skip middle 5 numbers ; Function to store primes in an array ; Function to find the smallest number which is not coprime with any element of the array arr [ ] ; Store the prime numbers ; Function call to fill the prime numbers ; Stores the answer ; Generate all non - empty subsets of the primes [ ] array ; Stores product of the primes ; Checks if temp is coprime with the array or not ; Check if the product temp is not coprime with the whole array ; If the product is not co - prime with the array ; Print the answer ; Driver Code ; Given array ; Stores the size of the array | MAX = 50 NEW_LINE import sys NEW_LINE from math import sqrt , gcd NEW_LINE def isPrime ( n ) : NEW_LINE INDENT if ( n <= 1 ) : NEW_LINE INDENT return False NEW_LINE DEDENT if ( n <= 3 ) : NEW_LINE INDENT return True NEW_LINE DEDENT if ( n % 2 == 0 or n % 3 == 0 ) : NEW_LINE INDENT return False NEW_LINE DEDENT for i in range ( 5 , int ( sqrt ( n ) ) + 1 , 6 ) : NEW_LINE INDENT if ( n % i == 0 or n % ( i + 2 ) == 0 ) : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT return True NEW_LINE DEDENT def findPrime ( primes ) : NEW_LINE INDENT global MAX NEW_LINE for i in range ( 2 , MAX + 1 , 1 ) : NEW_LINE INDENT if ( isPrime ( i ) ) : NEW_LINE INDENT primes . append ( i ) NEW_LINE DEDENT DEDENT DEDENT def findMinimumNumber ( arr , N ) : NEW_LINE INDENT primes = [ ] NEW_LINE findPrime ( primes ) NEW_LINE ans = sys . maxsize NEW_LINE n = len ( primes ) NEW_LINE for i in range ( 1 , ( 1 << n ) , 1 ) : NEW_LINE INDENT temp = 1 NEW_LINE for j in range ( n ) : NEW_LINE INDENT if ( i & ( 1 << j ) ) : NEW_LINE INDENT temp *= primes [ j ] NEW_LINE DEDENT DEDENT check = True NEW_LINE for k in range ( N ) : NEW_LINE INDENT if ( gcd ( temp , arr [ k ] ) == 1 ) : NEW_LINE INDENT check = False NEW_LINE break NEW_LINE DEDENT DEDENT if ( check ) : NEW_LINE INDENT ans = min ( ans , temp ) NEW_LINE DEDENT DEDENT print ( ans ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 3 , 4 , 6 , 7 , 8 , 9 , 10 ] NEW_LINE N = len ( arr ) NEW_LINE findMinimumNumber ( arr , N ) NEW_LINE DEDENT |
Count numbers from a given range that can be expressed as sum of digits raised to the power of count of digits | Python 3 program for the above approach ; Function to check if a number N can be expressed as sum of its digits raised to the power of the count of digits ; Stores the number of digits ; Stores the resultant number ; Return true if both the numbers are same ; Function to precompute and store for all numbers whether they can be expressed ; Mark all the index which are plus perfect number ; If true , then update the value at this index ; Compute prefix sum of the array ; Function to count array elements that can be expressed as the sum of digits raised to the power of count of digits ; Precompute the results ; Traverse the queries ; Print the resultant count ; Driver Code ; Function call | R = 100005 NEW_LINE arr = [ 0 for i in range ( R ) ] NEW_LINE def canExpress ( N ) : NEW_LINE INDENT temp = N NEW_LINE n = 0 NEW_LINE while ( N != 0 ) : NEW_LINE INDENT N //= 10 NEW_LINE n += 1 NEW_LINE DEDENT N = temp NEW_LINE sum = 0 NEW_LINE while ( N != 0 ) : NEW_LINE INDENT sum += pow ( N % 10 , n ) NEW_LINE N //= 10 NEW_LINE DEDENT return ( sum == temp ) NEW_LINE DEDENT def precompute ( ) : NEW_LINE INDENT for i in range ( 1 , R , 1 ) : NEW_LINE INDENT if ( canExpress ( i ) ) : NEW_LINE INDENT arr [ i ] = 1 NEW_LINE DEDENT DEDENT for i in range ( 1 , R , 1 ) : NEW_LINE INDENT arr [ i ] += arr [ i - 1 ] NEW_LINE DEDENT DEDENT def countNumbers ( queries , N ) : NEW_LINE INDENT precompute ( ) NEW_LINE for i in range ( N ) : NEW_LINE INDENT L1 = queries [ i ] [ 0 ] NEW_LINE R1 = queries [ i ] [ 1 ] NEW_LINE print ( ( arr [ R1 ] - arr [ L1 - 1 ] ) , end = " β " ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT queries = [ [ 1 , 400 ] , [ 1 , 9 ] ] NEW_LINE N = len ( queries ) NEW_LINE countNumbers ( queries , N ) NEW_LINE DEDENT |
Queries to calculate sum of the path from root to a given node in given Binary Tree | Function to find the sum of the path from root to the current node ; Sum of nodes in the path ; Iterate until root is reached ; Update the node value ; Print the resultant sum ; Function to print the path sum for each query ; Traverse the queries ; arraylist to store integers | def sumOfNodeInAPath ( node_value ) : NEW_LINE INDENT sum_of_node = 0 NEW_LINE while ( node_value ) : NEW_LINE INDENT sum_of_node += node_value NEW_LINE node_value //= 2 NEW_LINE DEDENT print ( sum_of_node , end = " β " ) NEW_LINE DEDENT def findSum ( Q ) : NEW_LINE INDENT for i in range ( len ( Q ) ) : NEW_LINE INDENT node_value = Q [ i ] NEW_LINE sumOfNodeInAPath ( node_value ) NEW_LINE print ( end = " " ) NEW_LINE DEDENT DEDENT arr = [ 1 , 5 , 20 , 100 ] NEW_LINE findSum ( arr ) NEW_LINE |
Minimum removals required to make frequency of all remaining array elements equal | Python 3 program for the above approach ; Function to count the minimum removals required to make frequency of all array elements equal ; Stores frequency of all array elements ; Traverse the array ; Stores all the frequencies ; Traverse the map ; Sort the frequencies ; Count of frequencies ; Stores the final count ; Traverse the vector ; Count the number of removals for each frequency and update the minimum removals required ; Print the final count ; Driver Code ; Given array ; Size of the array ; Function call to print the minimum number of removals required | from collections import defaultdict NEW_LINE def minDeletions ( arr , N ) : NEW_LINE INDENT freq = defaultdict ( int ) NEW_LINE for i in range ( N ) : NEW_LINE INDENT freq [ arr [ i ] ] += 1 NEW_LINE DEDENT v = [ ] NEW_LINE for z in freq . keys ( ) : NEW_LINE INDENT v . append ( freq [ z ] ) NEW_LINE DEDENT v . sort ( ) NEW_LINE size = len ( v ) NEW_LINE ans = N - ( v [ 0 ] * size ) NEW_LINE for i in range ( 1 , len ( v ) ) : NEW_LINE INDENT if ( v [ i ] != v [ i - 1 ] ) : NEW_LINE INDENT safe = v [ i ] * ( size - i ) NEW_LINE ans = min ( ans , N - safe ) NEW_LINE DEDENT DEDENT print ( ans ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 2 , 4 , 3 , 2 , 5 , 3 ] NEW_LINE N = len ( arr ) NEW_LINE minDeletions ( arr , N ) NEW_LINE DEDENT |
Check if a string is the typed name of the given name | Check if the character is vowel or not ; Returns true if ' typed ' is a typed name given str ; Traverse through all characters of str ; If current characters do not match ; If not vowel , simply move ahead in both ; Count occurrences of current vowel in str ; Count occurrence of current vowel in typed ; Driver code | def isVowel ( c ) : NEW_LINE INDENT vowel = " aeiou " NEW_LINE for i in range ( len ( vowel ) ) : NEW_LINE INDENT if ( vowel [ i ] == c ) : NEW_LINE INDENT return True NEW_LINE DEDENT DEDENT return False NEW_LINE DEDENT def printRLE ( str , typed ) : NEW_LINE INDENT n = len ( str ) NEW_LINE m = len ( typed ) NEW_LINE j = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT if str [ i ] != typed [ j ] : NEW_LINE INDENT return False NEW_LINE DEDENT if isVowel ( str [ i ] ) == False : NEW_LINE INDENT j = j + 1 NEW_LINE continue NEW_LINE DEDENT count1 = 1 NEW_LINE while ( i < n - 1 and ( str [ i ] == str [ i + 1 ] ) ) : NEW_LINE INDENT count1 = count1 + 1 NEW_LINE i = i + 1 NEW_LINE DEDENT count2 = 1 NEW_LINE while ( j < m - 1 and typed [ j ] == str [ i ] ) : NEW_LINE INDENT count2 = count2 + 1 NEW_LINE j = j + 1 NEW_LINE DEDENT if count1 > count2 : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT return True NEW_LINE DEDENT name = " alex " NEW_LINE typed = " aaalaeex " NEW_LINE if ( printRLE ( name , typed ) ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT |
Determine whether a universal sink exists in a directed graph | Python3 program to find whether a universal sink exists in a directed graph ; constructor to initialize number of vertices and size of adjacency matrix ; make adjacency_matrix [ i ] [ j ] = 1 if there is an edge from i to j ; if any element in the row i is 1 , it means that there is an edge emanating from the vertex , which means it cannot be a sink ; if any element other than i in the column i is 0 , it means that there is no edge from that vertex to the vertex we are testing and hence it cannot be a sink ; if none of the checks fails , return true ; we will eliminate n - 1 non sink vertices so that we have to check for only one vertex instead of all n vertices ; If the index is 1 , increment the row we are checking by 1 else increment the column ; If i exceeds the number of vertices , it means that there is no valid vertex in the given vertices that can be a sink ; Driver Code ; input set 1 g . insert ( 1 , 6 ) g . insert ( 2 , 6 ) g . insert ( 3 , 6 ) g . insert ( 4 , 6 ) g . insert ( 5 , 6 ) input set 2 ; returns 0 based indexing of vertex . returns - 1 if no sink exits . returns the vertex number - 1 if sink is found | class Graph : NEW_LINE INDENT def __init__ ( self , vertices ) : NEW_LINE INDENT self . vertices = vertices NEW_LINE self . adjacency_matrix = [ [ 0 for i in range ( vertices ) ] for j in range ( vertices ) ] NEW_LINE DEDENT def insert ( self , s , destination ) : NEW_LINE INDENT self . adjacency_matrix [ s - 1 ] [ destination - 1 ] = 1 NEW_LINE DEDENT def issink ( self , i ) : NEW_LINE INDENT for j in range ( self . vertices ) : NEW_LINE INDENT if self . adjacency_matrix [ i ] [ j ] == 1 : NEW_LINE INDENT return False NEW_LINE DEDENT if self . adjacency_matrix [ j ] [ i ] == 0 and j != i : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT return True NEW_LINE DEDENT def eliminate ( self ) : NEW_LINE INDENT i = 0 NEW_LINE j = 0 NEW_LINE while i < self . vertices and j < self . vertices : NEW_LINE INDENT if self . adjacency_matrix [ i ] [ j ] == 1 : NEW_LINE INDENT i += 1 NEW_LINE DEDENT else : NEW_LINE INDENT j += 1 NEW_LINE DEDENT DEDENT if i > self . vertices : NEW_LINE INDENT return - 1 NEW_LINE DEDENT elif self . issink ( i ) is False : NEW_LINE INDENT return - 1 NEW_LINE DEDENT else : NEW_LINE INDENT return i NEW_LINE DEDENT DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT number_of_vertices = 6 NEW_LINE number_of_edges = 5 NEW_LINE g = Graph ( number_of_vertices ) NEW_LINE g . insert ( 1 , 6 ) NEW_LINE g . insert ( 2 , 3 ) NEW_LINE g . insert ( 2 , 4 ) NEW_LINE g . insert ( 4 , 3 ) NEW_LINE g . insert ( 5 , 3 ) NEW_LINE vertex = g . eliminate ( ) NEW_LINE if vertex >= 0 : NEW_LINE INDENT print ( " Sink β found β at β vertex β % d " % ( vertex + 1 ) ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No β Sink " ) NEW_LINE DEDENT DEDENT |
Reverse alternate levels of a perfect binary tree | Python3 program to reverse alternate levels of a tree A Binary Tree Node Utility function to create a new tree node ; Base cases ; Swap subtrees if level is even ; Recur for left and right subtrees ( Note : left of root1 is passed and right of root2 in first call and opposite in second call . ; This function calls preorder ( ) for left and right children of root ; Inorder traversal ( used to print initial and modified trees ) ; A utility function to create a new node ; Driver Code | class Node : NEW_LINE INDENT def __init__ ( self , key ) : NEW_LINE INDENT self . key = key NEW_LINE self . left = None NEW_LINE self . right = None NEW_LINE DEDENT DEDENT def preorder ( root1 , root2 , lvl ) : NEW_LINE INDENT if ( root1 == None or root2 == None ) : NEW_LINE INDENT return NEW_LINE DEDENT if ( lvl % 2 == 0 ) : NEW_LINE INDENT t = root1 . key NEW_LINE root1 . key = root2 . key NEW_LINE root2 . key = t NEW_LINE DEDENT preorder ( root1 . left , root2 . right , lvl + 1 ) NEW_LINE preorder ( root1 . right , root2 . left , lvl + 1 ) NEW_LINE DEDENT def reverseAlternate ( root ) : NEW_LINE INDENT preorder ( root . left , root . right , 0 ) NEW_LINE DEDENT def printInorder ( root ) : NEW_LINE INDENT if ( root == None ) : NEW_LINE INDENT return NEW_LINE DEDENT printInorder ( root . left ) NEW_LINE print ( root . key , end = " β " ) NEW_LINE printInorder ( root . right ) NEW_LINE DEDENT def newNode ( key ) : NEW_LINE INDENT temp = Node ( ' β ' ) NEW_LINE temp . left = temp . right = None NEW_LINE temp . key = key NEW_LINE return temp NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT root = newNode ( ' a ' ) NEW_LINE root . left = newNode ( ' b ' ) NEW_LINE root . right = newNode ( ' c ' ) NEW_LINE root . left . left = newNode ( ' d ' ) NEW_LINE root . left . right = newNode ( ' e ' ) NEW_LINE root . right . left = newNode ( ' f ' ) NEW_LINE root . right . right = newNode ( ' g ' ) NEW_LINE root . left . left . left = newNode ( ' h ' ) NEW_LINE root . left . left . right = newNode ( ' i ' ) NEW_LINE root . left . right . left = newNode ( ' j ' ) NEW_LINE root . left . right . right = newNode ( ' k ' ) NEW_LINE root . right . left . left = newNode ( ' l ' ) NEW_LINE root . right . left . right = newNode ( ' m ' ) NEW_LINE root . right . right . left = newNode ( ' n ' ) NEW_LINE root . right . right . right = newNode ( ' o ' ) NEW_LINE print ( " Inorder β Traversal β of β given β tree " ) NEW_LINE printInorder ( root ) NEW_LINE reverseAlternate ( root ) NEW_LINE print ( " Inorder Traversal of modified tree " ) NEW_LINE printInorder ( root ) NEW_LINE DEDENT |
Deletion in a Binary Tree | class to create a node with data , left child and right child . ; Inorder traversal of a binary tree ; function to delete the given deepest node ( d_node ) in binary tree ; Do level order traversal until last node ; function to delete element in binary tree ; Do level order traversal to find deepest node ( temp ) and node to be deleted ( key_node ) ; Driver code | class Node : NEW_LINE INDENT def __init__ ( self , data ) : NEW_LINE INDENT self . data = data NEW_LINE self . left = None NEW_LINE self . right = None NEW_LINE DEDENT DEDENT def inorder ( temp ) : NEW_LINE INDENT if ( not temp ) : NEW_LINE INDENT return NEW_LINE DEDENT inorder ( temp . left ) NEW_LINE print ( temp . data , end = " β " ) NEW_LINE inorder ( temp . right ) NEW_LINE DEDENT def deleteDeepest ( root , d_node ) : NEW_LINE INDENT q = [ ] NEW_LINE q . append ( root ) NEW_LINE while ( len ( q ) ) : NEW_LINE INDENT temp = q . pop ( 0 ) NEW_LINE if temp is d_node : NEW_LINE INDENT temp = None NEW_LINE return NEW_LINE DEDENT if temp . right : NEW_LINE INDENT if temp . right is d_node : NEW_LINE INDENT temp . right = None NEW_LINE return NEW_LINE DEDENT else : NEW_LINE INDENT q . append ( temp . right ) NEW_LINE DEDENT DEDENT if temp . left : NEW_LINE INDENT if temp . left is d_node : NEW_LINE INDENT temp . left = None NEW_LINE return NEW_LINE DEDENT else : NEW_LINE INDENT q . append ( temp . left ) NEW_LINE DEDENT DEDENT DEDENT DEDENT def deletion ( root , key ) : NEW_LINE INDENT if root == None : NEW_LINE INDENT return None NEW_LINE DEDENT if root . left == None and root . right == None : NEW_LINE INDENT if root . key == key : NEW_LINE INDENT return None NEW_LINE DEDENT else : NEW_LINE INDENT return root NEW_LINE DEDENT DEDENT key_node = None NEW_LINE q = [ ] NEW_LINE q . append ( root ) NEW_LINE while ( len ( q ) ) : NEW_LINE INDENT temp = q . pop ( 0 ) NEW_LINE if temp . data == key : NEW_LINE INDENT key_node = temp NEW_LINE DEDENT if temp . left : NEW_LINE INDENT q . append ( temp . left ) NEW_LINE DEDENT if temp . right : NEW_LINE INDENT q . append ( temp . right ) NEW_LINE DEDENT DEDENT if key_node : NEW_LINE INDENT x = temp . data NEW_LINE deleteDeepest ( root , temp ) NEW_LINE key_node . data = x NEW_LINE DEDENT return root NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT root = Node ( 10 ) NEW_LINE root . left = Node ( 11 ) NEW_LINE root . left . left = Node ( 7 ) NEW_LINE root . left . right = Node ( 12 ) NEW_LINE root . right = Node ( 9 ) NEW_LINE root . right . left = Node ( 15 ) NEW_LINE root . right . right = Node ( 8 ) NEW_LINE print ( " The β tree β before β the β deletion : " ) NEW_LINE inorder ( root ) NEW_LINE key = 11 NEW_LINE root = deletion ( root , key ) NEW_LINE print ( ) NEW_LINE print ( " The β tree β after β the β deletion ; " ) NEW_LINE inorder ( root ) NEW_LINE DEDENT |
Number of sink nodes in a graph | Return the number of Sink NOdes . ; Array for marking the non - sink node . ; Marking the non - sink node . ; Counting the sink nodes . ; Driver Code | def countSink ( n , m , edgeFrom , edgeTo ) : NEW_LINE INDENT mark = [ 0 ] * ( n + 1 ) NEW_LINE for i in range ( m ) : NEW_LINE INDENT mark [ edgeFrom [ i ] ] = 1 NEW_LINE DEDENT count = 0 NEW_LINE for i in range ( 1 , n + 1 ) : NEW_LINE INDENT if ( not mark [ i ] ) : NEW_LINE INDENT count += 1 NEW_LINE DEDENT DEDENT return count NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT n = 4 NEW_LINE m = 2 NEW_LINE edgeFrom = [ 2 , 4 ] NEW_LINE edgeTo = [ 3 , 3 ] NEW_LINE print ( countSink ( n , m , edgeFrom , edgeTo ) ) NEW_LINE DEDENT |
Largest subset of Graph vertices with edges of 2 or more colors | Number of vertices ; function to calculate max subset size ; set for number of vertices ; loop for deletion of vertex from set ; if subset has only 1 vertex return 0 ; for each vertex iterate and keep removing a vertix while we find a vertex with all edges of same color . ; note down different color values for each vertex ; if only one color is found erase that vertex ( bad vertex ) ; If no vertex was removed in the above loop . ; Driver Code | N = 6 NEW_LINE def subsetGraph ( C ) : NEW_LINE INDENT global N NEW_LINE vertices = set ( ) NEW_LINE for i in range ( N ) : NEW_LINE INDENT vertices . add ( i ) NEW_LINE DEDENT while ( len ( vertices ) != 0 ) : NEW_LINE INDENT if ( len ( vertices ) == 1 ) : NEW_LINE INDENT return 1 NEW_LINE DEDENT someone_removed = False NEW_LINE for x in vertices : NEW_LINE INDENT values = set ( ) NEW_LINE for y in vertices : NEW_LINE INDENT if ( y != x ) : NEW_LINE INDENT values . add ( C [ x ] [ y ] ) NEW_LINE DEDENT DEDENT if ( len ( values ) == 1 ) : NEW_LINE INDENT vertices . remove ( x ) NEW_LINE someone_removed = True NEW_LINE break NEW_LINE DEDENT DEDENT if ( not someone_removed ) : NEW_LINE INDENT break NEW_LINE DEDENT DEDENT return len ( vertices ) NEW_LINE DEDENT C = [ [ 0 , 9 , 2 , 4 , 7 , 8 ] , [ 9 , 0 , 9 , 9 , 7 , 9 ] , [ 2 , 9 , 0 , 3 , 7 , 6 ] , [ 4 , 9 , 3 , 0 , 7 , 1 ] , [ 7 , 7 , 7 , 7 , 0 , 7 ] , [ 8 , 9 , 6 , 1 , 7 , 0 ] ] NEW_LINE print ( subsetGraph ( C ) ) NEW_LINE |
Count number of edges in an undirected graph | Adjacency list representation of graph ; add edge to graph ; Returns count of edge in undirected graph ; traverse all vertex ; add all edge that are linked to the current vertex ; The count of edge is always even because in undirected graph every edge is connected twice between two vertices ; Driver Code ; making above uhown graph | class Graph : NEW_LINE INDENT def __init__ ( self , V ) : NEW_LINE INDENT self . V = V NEW_LINE self . adj = [ [ ] for i in range ( V ) ] NEW_LINE DEDENT def addEdge ( self , u , v ) : NEW_LINE INDENT self . adj [ u ] . append ( v ) NEW_LINE self . adj [ v ] . append ( u ) NEW_LINE DEDENT def countEdges ( self ) : NEW_LINE INDENT Sum = 0 NEW_LINE for i in range ( self . V ) : NEW_LINE INDENT Sum += len ( self . adj [ i ] ) NEW_LINE DEDENT return Sum // 2 NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT V = 9 NEW_LINE g = Graph ( V ) NEW_LINE g . addEdge ( 0 , 1 ) NEW_LINE g . addEdge ( 0 , 7 ) NEW_LINE g . addEdge ( 1 , 2 ) NEW_LINE g . addEdge ( 1 , 7 ) NEW_LINE g . addEdge ( 2 , 3 ) NEW_LINE g . addEdge ( 2 , 8 ) NEW_LINE g . addEdge ( 2 , 5 ) NEW_LINE g . addEdge ( 3 , 4 ) NEW_LINE g . addEdge ( 3 , 5 ) NEW_LINE g . addEdge ( 4 , 5 ) NEW_LINE g . addEdge ( 5 , 6 ) NEW_LINE g . addEdge ( 6 , 7 ) NEW_LINE g . addEdge ( 6 , 8 ) NEW_LINE g . addEdge ( 7 , 8 ) NEW_LINE print ( g . countEdges ( ) ) NEW_LINE DEDENT |
Two Clique Problem ( Check if Graph can be divided in two Cliques ) | Python3 program to find out whether a given graph can be converted to two Cliques or not . ; This function returns true if subgraph reachable from src is Bipartite or not . ; Create a queue ( FIFO ) of vertex numbers and enqueue source vertex for BFS traversal ; Run while there are vertices in queue ( Similar to BFS ) ; Dequeue a vertex from queue ; Find all non - colored adjacent vertices ; An edge from u to v exists and destination v is not colored ; Assign alternate color to this adjacent v of u ; An edge from u to v exists and destination v is colored with same color as u ; If we reach here , then all adjacent vertices can be colored with alternate color ; Returns true if a Graph G [ ] [ ] is Bipartite or not . Note that G may not be connected . ; Create a color array to store colors assigned to all veritces . Vertex number is used as index in this array . The value ' - 1' of colorArr [ i ] is used to indicate that no color is assigned to vertex ' i ' . The value 1 is used to indicate first color is assigned and value 0 indicates second color is assigned . ; One by one check all not yet colored vertices . ; Returns true if G can be divided into two Cliques , else false . ; Find complement of G [ ] [ ] All values are complemented except diagonal ones ; Return true if complement is Bipartite else false . ; Driver Code | from queue import Queue NEW_LINE def isBipartiteUtil ( G , src , colorArr ) : NEW_LINE INDENT global V NEW_LINE colorArr [ src ] = 1 NEW_LINE q = Queue ( ) NEW_LINE q . put ( src ) NEW_LINE while ( not q . empty ( ) ) : NEW_LINE INDENT u = q . get ( ) NEW_LINE for v in range ( V ) : NEW_LINE INDENT if ( G [ u ] [ v ] and colorArr [ v ] == - 1 ) : NEW_LINE INDENT colorArr [ v ] = 1 - colorArr [ u ] NEW_LINE q . put ( v ) NEW_LINE DEDENT elif ( G [ u ] [ v ] and colorArr [ v ] == colorArr [ u ] ) : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT DEDENT return True NEW_LINE DEDENT def isBipartite ( G ) : NEW_LINE INDENT global V NEW_LINE colorArr = [ - 1 ] * V NEW_LINE for i in range ( V ) : NEW_LINE INDENT if ( colorArr [ i ] == - 1 ) : NEW_LINE INDENT if ( isBipartiteUtil ( G , i , colorArr ) == False ) : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT DEDENT return True NEW_LINE DEDENT def canBeDividedinTwoCliques ( G ) : NEW_LINE INDENT global V NEW_LINE GC = [ [ None ] * V for i in range ( V ) ] NEW_LINE for i in range ( V ) : NEW_LINE INDENT for j in range ( V ) : NEW_LINE INDENT GC [ i ] [ j ] = not G [ i ] [ j ] if i != j else 0 NEW_LINE DEDENT DEDENT return isBipartite ( GC ) NEW_LINE DEDENT V = 5 NEW_LINE G = [ [ 0 , 1 , 1 , 1 , 0 ] , [ 1 , 0 , 1 , 0 , 0 ] , [ 1 , 1 , 0 , 0 , 0 ] , [ 0 , 1 , 0 , 0 , 1 ] , [ 0 , 0 , 0 , 1 , 0 ] ] NEW_LINE if canBeDividedinTwoCliques ( G ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT |
Check whether given degrees of vertices represent a Graph or Tree | Function returns true for tree false for graph ; Find sum of all degrees ; It is tree if sum is equal to 2 ( n - 1 ) ; main | def check ( degree , n ) : NEW_LINE INDENT deg_sum = sum ( degree ) NEW_LINE if ( 2 * ( n - 1 ) == deg_sum ) : NEW_LINE INDENT return True NEW_LINE DEDENT else : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT n = 5 NEW_LINE degree = [ 2 , 3 , 1 , 1 , 1 ] ; NEW_LINE if ( check ( degree , n ) ) : NEW_LINE INDENT print " Tree " NEW_LINE DEDENT else : NEW_LINE INDENT print " Graph " NEW_LINE DEDENT |
Finding minimum vertex cover size of a graph using binary search | A Python3 program to find size of minimum vertex cover using Binary Search ; Global array to store the graph Note : since the array is global , all the elements are 0 initially ; Returns true if there is a possible subSet of size ' k ' that can be a vertex cover ; Set has first ' k ' bits high initially ; to mark the edges covered in each subSet of size ' k ' ; ReSet visited array for every subSet of vertices ; Set counter for number of edges covered from this subSet of vertices to zero ; selected vertex cover is the indices where ' Set ' has its bit high ; Mark all edges emerging out of this vertex visited ; If the current subSet covers all the edges ; Generate previous combination with k bits high Set & - Set = ( 1 << last bit high in Set ) ; Returns answer to graph stored in gr [ ] [ ] ; Binary search the answer ; at the end of while loop both left and right will be equal , / as when they are not , the while loop won 't exit the minimum size vertex cover = left = right ; Inserts an edge in the graph ; Undirected graph ; 6 / 1 -- -- - 5 vertex cover = { 1 , 2 } / | \ 3 | \ \ | \ 2 4 ; Let us create another graph ; 2 -- -- 4 -- -- 6 / | | 1 | | vertex cover = { 2 , 3 , 4 } \ | | 3 -- -- 5 | maxn = 25 NEW_LINE gr = [ [ None ] * maxn for i in range ( maxn ) ] NEW_LINE def isCover ( V , k , E ) : NEW_LINE INDENT Set = ( 1 << k ) - 1 NEW_LINE limit = ( 1 << V ) NEW_LINE vis = [ [ None ] * maxn for i in range ( maxn ) ] NEW_LINE while ( Set < limit ) : NEW_LINE INDENT vis = [ [ 0 ] * maxn for i in range ( maxn ) ] NEW_LINE cnt = 0 NEW_LINE j = 1 NEW_LINE v = 1 NEW_LINE while ( j < limit ) : NEW_LINE INDENT if ( Set & j ) : NEW_LINE INDENT for k in range ( 1 , V + 1 ) : NEW_LINE INDENT if ( gr [ v ] [ k ] and not vis [ v ] [ k ] ) : NEW_LINE INDENT vis [ v ] [ k ] = 1 NEW_LINE vis [ k ] [ v ] = 1 NEW_LINE cnt += 1 NEW_LINE DEDENT DEDENT DEDENT j = j << 1 NEW_LINE v += 1 NEW_LINE DEDENT if ( cnt == E ) : NEW_LINE INDENT return True NEW_LINE DEDENT c = Set & - Set NEW_LINE r = Set + c NEW_LINE Set = ( ( ( r ^ Set ) >> 2 ) // c ) | r NEW_LINE DEDENT return False NEW_LINE DEDENT def findMinCover ( n , m ) : NEW_LINE INDENT left = 1 NEW_LINE right = n NEW_LINE while ( right > left ) : NEW_LINE INDENT mid = ( left + right ) >> 1 NEW_LINE if ( isCover ( n , mid , m ) == False ) : NEW_LINE INDENT left = mid + 1 NEW_LINE DEDENT else : NEW_LINE INDENT right = mid NEW_LINE DEDENT DEDENT return left NEW_LINE DEDENT def insertEdge ( u , v ) : NEW_LINE INDENT gr [ u ] [ v ] = 1 NEW_LINE gr [ v ] [ u ] = 1 NEW_LINE DEDENT V = 6 NEW_LINE E = 6 NEW_LINE insertEdge ( 1 , 2 ) NEW_LINE insertEdge ( 2 , 3 ) NEW_LINE insertEdge ( 1 , 3 ) NEW_LINE insertEdge ( 1 , 4 ) NEW_LINE insertEdge ( 1 , 5 ) NEW_LINE insertEdge ( 1 , 6 ) NEW_LINE print ( " Minimum β size β of β a β vertex β cover β = β " , findMinCover ( V , E ) ) NEW_LINE gr = [ [ 0 ] * maxn for i in range ( maxn ) ] NEW_LINE V = 6 NEW_LINE E = 7 NEW_LINE insertEdge ( 1 , 2 ) NEW_LINE insertEdge ( 1 , 3 ) NEW_LINE insertEdge ( 2 , 3 ) NEW_LINE insertEdge ( 2 , 4 ) NEW_LINE insertEdge ( 3 , 5 ) NEW_LINE insertEdge ( 4 , 5 ) NEW_LINE insertEdge ( 4 , 6 ) NEW_LINE print ( " Minimum β size β of β a β vertex β cover β = β " , findMinCover ( V , E ) ) NEW_LINE |
Morris traversal for Preorder | Python program for Morris Preorder traversal A binary tree Node ; Preorder traversal without recursion and without stack ; If left child is null , print the current node data . And , update the current pointer to right child . ; Find the inorder predecessor ; If the right child of inorder predecessor already points to the current node , update the current with it 's right child ; else If right child doesn ' t β point β β to β the β current β node , β then β print β this β β node ' s data and update the right child pointer with the current node and update the current with it 's left child ; Function for sStandard preorder traversal ; Driver program to test | class Node : NEW_LINE INDENT def __init__ ( self , data ) : NEW_LINE INDENT self . data = data NEW_LINE self . left = None NEW_LINE self . right = None NEW_LINE DEDENT DEDENT def MorrisTraversal ( root ) : NEW_LINE INDENT curr = root NEW_LINE while curr : NEW_LINE INDENT if curr . left is None : NEW_LINE INDENT print ( curr . data , end = " β " ) NEW_LINE curr = curr . right NEW_LINE DEDENT else : NEW_LINE INDENT prev = curr . left NEW_LINE while prev . right is not None and prev . right is not curr : NEW_LINE INDENT prev = prev . right NEW_LINE DEDENT if prev . right is curr : NEW_LINE INDENT prev . right = None NEW_LINE curr = curr . right NEW_LINE DEDENT else : NEW_LINE INDENT print ( curr . data , end = " β " ) NEW_LINE prev . right = curr NEW_LINE curr = curr . left NEW_LINE DEDENT DEDENT DEDENT DEDENT def preorfer ( root ) : NEW_LINE INDENT if root : NEW_LINE INDENT print ( root . data , end = " β " ) NEW_LINE preorfer ( root . left ) NEW_LINE preorfer ( root . right ) NEW_LINE DEDENT DEDENT root = Node ( 1 ) NEW_LINE root . left = Node ( 2 ) NEW_LINE root . right = Node ( 3 ) NEW_LINE root . left . left = Node ( 4 ) NEW_LINE root . left . right = Node ( 5 ) NEW_LINE root . right . left = Node ( 6 ) NEW_LINE root . right . right = Node ( 7 ) NEW_LINE root . left . left . left = Node ( 8 ) NEW_LINE root . left . left . right = Node ( 9 ) NEW_LINE root . left . right . left = Node ( 10 ) NEW_LINE root . left . right . right = Node ( 11 ) NEW_LINE MorrisTraversal ( root ) NEW_LINE print ( " " ) NEW_LINE preorfer ( root ) NEW_LINE |
Subsets and Splits