text
stringlengths
17
3.65k
code
stringlengths
70
5.84k
Number of triangles formed by joining vertices of n | Function to find the number of triangles ; print the number of triangles ; ; Driver code initialize the number of sides of a polygon
def findTriangles ( n ) : NEW_LINE INDENT num = n * ( n - 4 ) NEW_LINE print ( num ) NEW_LINE DEDENT / * Driver code * / NEW_LINE n = 6 NEW_LINE findTriangles ( n ) NEW_LINE
Find the Diameter or Longest chord of a Circle | Function to find the longest chord ; Get the radius ; Find the diameter
def diameter ( r ) : NEW_LINE INDENT print ( " The ▁ length ▁ of ▁ the ▁ longest ▁ chord " , " ▁ or ▁ diameter ▁ of ▁ the ▁ circle ▁ is ▁ " , 2 * r ) NEW_LINE DEDENT r = 4 NEW_LINE diameter ( r ) NEW_LINE
Slope of the line parallel to the line with the given slope | Function to return the slope of the line which is parallel to the line with the given slope ; Driver code
def getSlope ( m ) : NEW_LINE INDENT return m ; NEW_LINE DEDENT m = 2 ; NEW_LINE print ( getSlope ( m ) ) ; NEW_LINE
Total number of triangles formed when there are H horizontal and V vertical lines | Function to return total triangles ; Only possible triangle is the given triangle ; If only vertical lines are present ; If only horizontal lines are present ; Return total triangles ; Driver code
def totalTriangles ( h , v ) : NEW_LINE INDENT if ( h == 0 and v == 0 ) : NEW_LINE INDENT return 1 NEW_LINE DEDENT if ( h == 0 ) : NEW_LINE INDENT return ( ( v + 1 ) * ( v + 2 ) / 2 ) NEW_LINE DEDENT if ( v == 0 ) : NEW_LINE INDENT return ( h + 1 ) NEW_LINE DEDENT total = ( h + 1 ) * ( ( v + 1 ) * ( v + 2 ) / 2 ) NEW_LINE return total NEW_LINE DEDENT h = 2 NEW_LINE v = 2 NEW_LINE print ( int ( totalTriangles ( h , v ) ) ) NEW_LINE
Largest sphere that can be inscribed in a right circular cylinder inscribed in a frustum | Python3 Program to find the biggest sphere that can be inscribed within a right circular cylinder which in turn is inscribed within a frustum ; Function to find the biggest sphere ; the radii and height cannot be negative ; radius of the sphere ; volume of the sphere ; Driver code
import math as mt NEW_LINE def sph ( r , R , h ) : NEW_LINE INDENT if ( r < 0 and R < 0 and h < 0 ) : NEW_LINE INDENT return - 1 NEW_LINE DEDENT x = r NEW_LINE V = ( 4 * 3.14 * pow ( r , 3 ) ) / 3 NEW_LINE return V NEW_LINE DEDENT r , R , h = 5 , 8 , 11 NEW_LINE print ( sph ( r , R , h ) ) NEW_LINE
Check whether two straight lines are orthogonal or not | Function to check if two straight lines are orthogonal or not ; Both lines have infinite slope ; Only line 1 has infinite slope ; Only line 2 has infinite slope ; Find slopes of the lines ; Check if their product is - 1 ; Driver code
def checkOrtho ( x1 , y1 , x2 , y2 , x3 , y3 , x4 , y4 ) : NEW_LINE INDENT if ( x2 - x1 == 0 and x4 - x3 == 0 ) : NEW_LINE INDENT return False NEW_LINE DEDENT elif ( x2 - x1 == 0 ) : NEW_LINE INDENT m2 = ( y4 - y3 ) / ( x4 - x3 ) NEW_LINE if ( m2 == 0 ) : NEW_LINE INDENT return True NEW_LINE DEDENT else : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT elif ( x4 - x3 == 0 ) : NEW_LINE INDENT m1 = ( y2 - y1 ) / ( x2 - x1 ) ; NEW_LINE if ( m1 == 0 ) : NEW_LINE INDENT return True NEW_LINE DEDENT else : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT else : NEW_LINE INDENT m1 = ( y2 - y1 ) / ( x2 - x1 ) NEW_LINE m2 = ( y4 - y3 ) / ( x4 - x3 ) NEW_LINE if ( m1 * m2 == - 1 ) : NEW_LINE INDENT return True NEW_LINE DEDENT else : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT x1 = 0 NEW_LINE y1 = 4 NEW_LINE x2 = 0 NEW_LINE y2 = - 9 NEW_LINE x3 = 2 NEW_LINE y3 = 0 NEW_LINE x4 = - 1 NEW_LINE y4 = 0 NEW_LINE if ( checkOrtho ( x1 , y1 , x2 , y2 , x3 , y3 , x4 , y4 ) ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT DEDENT
Diagonal of a Regular Pentagon | Function to find the diagonal of a regular pentagon ; Side cannot be negative ; Length of the diagonal ; Driver code
def pentdiagonal ( a ) : NEW_LINE INDENT if ( a < 0 ) : NEW_LINE INDENT return - 1 NEW_LINE DEDENT d = 1.22 * a NEW_LINE return d NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT a = 6 NEW_LINE print ( pentdiagonal ( a ) ) NEW_LINE DEDENT
Area of hexagon with given diagonal length | Python3 program to find the area of Hexagon with given diagonal ; Function to calculate area ; Formula to find area ; Driver ode
from math import sqrt NEW_LINE def hexagonArea ( d ) : NEW_LINE INDENT return ( 3 * sqrt ( 3 ) * pow ( d , 2 ) ) / 8 NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT d = 10 NEW_LINE print ( " Area ▁ of ▁ hexagon : " , round ( hexagonArea ( d ) , 3 ) ) NEW_LINE DEDENT
Number of squares of side length required to cover an N * M rectangle | function to find number of squares of a * a required to cover n * m rectangle ; Driver code ; function call
def Squares ( n , m , a ) : NEW_LINE INDENT return ( ( ( m + a - 1 ) // a ) * ( ( n + a - 1 ) // a ) ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT n = 6 NEW_LINE m = 6 NEW_LINE a = 4 NEW_LINE print ( Squares ( n , m , a ) ) NEW_LINE DEDENT
Length of the Diagonal of the Octagon | Python3 Program to find the diagonal of the octagon ; Function to find the diagonal of the octagon ; side cannot be negative ; diagonal of the octagon ; Driver code
import math NEW_LINE def octadiagonal ( a ) : NEW_LINE INDENT if ( a < 0 ) : NEW_LINE INDENT return - 1 ; NEW_LINE DEDENT return a * math . sqrt ( 4 + ( 2 * math . sqrt ( 2 ) ) ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT a = 4 NEW_LINE print ( octadiagonal ( a ) ) NEW_LINE DEDENT
Program to Calculate the Perimeter of a Decagon | Function for finding the perimeter ; Driver code
def CalPeri ( ) : NEW_LINE INDENT s = 5 NEW_LINE Perimeter = 10 * s NEW_LINE print ( " The ▁ Perimeter ▁ of ▁ Decagon ▁ is ▁ : ▁ " , Perimeter ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT CalPeri ( ) ; NEW_LINE DEDENT
Sum of lengths of all 12 edges of any rectangular parallelepiped | Python3 program to illustrate the above problem ; function to find the sum of all the edges of parallelepiped ; to calculate the length of one edge ; sum of all the edges of one side ; net sum will be equal to the summation of edges of all the sides ; Driver code ; initialize the area of three faces which has a common vertex
import math NEW_LINE def findEdges ( s1 , s2 , s3 ) : NEW_LINE INDENT a = math . sqrt ( s1 * s2 / s3 ) NEW_LINE b = math . sqrt ( s3 * s1 / s2 ) NEW_LINE c = math . sqrt ( s3 * s2 / s1 ) NEW_LINE sum = a + b + c NEW_LINE return 4 * sum NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT s1 = 65 NEW_LINE s2 = 156 NEW_LINE s3 = 60 NEW_LINE print ( int ( findEdges ( s1 , s2 , s3 ) ) ) NEW_LINE DEDENT
Maximum number of pieces in N cuts | Function for finding maximum pieces with n cuts . ; to maximize number of pieces x is the horizontal cuts ; Now ( x ) is the horizontal cuts and ( n - x ) is vertical cuts , then maximum number of pieces = ( x + 1 ) * ( n - x + 1 ) ; Driver code ; Taking the maximum number of cuts allowed as 3 ; Finding and printing the max number of pieces
def findMaximumPieces ( n ) : NEW_LINE INDENT x = n // 2 NEW_LINE return ( ( x + 1 ) * ( n - x + 1 ) ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT n = 3 NEW_LINE print ( " Max ▁ number ▁ of ▁ pieces ▁ for ▁ n ▁ = ▁ " + str ( n ) + " ▁ is ▁ " + str ( findMaximumPieces ( 3 ) ) ) NEW_LINE DEDENT
Program to check whether 4 points in a 3 | Function to find equation of plane . ; checking if the 4 th point satisfies the above equation ; Driver Code ;
def equation_plane ( x1 , y1 , z1 , x2 , y2 , z2 , x3 , y3 , z3 , x , y , z ) : NEW_LINE INDENT a1 = x2 - x1 NEW_LINE b1 = y2 - y1 NEW_LINE c1 = z2 - z1 NEW_LINE a2 = x3 - x1 NEW_LINE b2 = y3 - y1 NEW_LINE c2 = z3 - z1 NEW_LINE a = b1 * c2 - b2 * c1 NEW_LINE b = a2 * c1 - a1 * c2 NEW_LINE c = a1 * b2 - b1 * a2 NEW_LINE d = ( - a * x1 - b * y1 - c * z1 ) NEW_LINE if ( a * x + b * y + c * z + d == 0 ) : NEW_LINE INDENT print ( " Coplanar " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " Not ▁ Coplanar " ) NEW_LINE DEDENT DEDENT x1 = 3 NEW_LINE y1 = 2 NEW_LINE z1 = - 5 NEW_LINE x2 = - 1 NEW_LINE y2 = 4 NEW_LINE z2 = - 3 NEW_LINE x3 = - 3 NEW_LINE y3 = 8 NEW_LINE z3 = - 5 NEW_LINE x4 = - 3 NEW_LINE y4 = 2 NEW_LINE z4 = 1 NEW_LINE / * function calling * / NEW_LINE equation_plane ( x1 , y1 , z1 , x2 , y2 , z2 , x3 , y3 , z3 , x4 , y4 , z4 ) NEW_LINE
Angle between two Planes in 3D | Python program to find the Angle between two Planes in 3 D . ; Function to find Angle ; Driver Code
import math NEW_LINE def distance ( a1 , b1 , c1 , a2 , b2 , c2 ) : NEW_LINE INDENT d = ( a1 * a2 + b1 * b2 + c1 * c2 ) NEW_LINE e1 = math . sqrt ( a1 * a1 + b1 * b1 + c1 * c1 ) NEW_LINE e2 = math . sqrt ( a2 * a2 + b2 * b2 + c2 * c2 ) NEW_LINE d = d / ( e1 * e2 ) NEW_LINE A = math . degrees ( math . acos ( d ) ) NEW_LINE print ( " Angle ▁ is " ) , A , ( " degree " ) NEW_LINE DEDENT a1 = 1 NEW_LINE b1 = 1 NEW_LINE c1 = 2 NEW_LINE d1 = 1 NEW_LINE a2 = 2 NEW_LINE b2 = - 1 NEW_LINE c2 = 1 NEW_LINE d2 = - 4 NEW_LINE distance ( a1 , b1 , c1 , a2 , b2 , c2 ) NEW_LINE
Mirror of a point through a 3 D plane | Function to mirror image ; Driver Code ; function call
def mirror_point ( a , b , c , d , x1 , y1 , z1 ) : NEW_LINE INDENT k = ( - a * x1 - b * y1 - c * z1 - d ) / float ( ( a * a + b * b + c * c ) ) NEW_LINE x2 = a * k + x1 NEW_LINE y2 = b * k + y1 NEW_LINE z2 = c * k + z1 NEW_LINE x3 = 2 * x2 - x1 NEW_LINE y3 = 2 * y2 - y1 NEW_LINE z3 = 2 * z2 - z1 NEW_LINE print " x3 ▁ = " , x3 , NEW_LINE print " y3 ▁ = " , y3 , NEW_LINE print " z3 ▁ = " , z3 , NEW_LINE DEDENT a = 1 NEW_LINE b = - 2 NEW_LINE c = 0 NEW_LINE d = 0 NEW_LINE x1 = - 1 NEW_LINE y1 = 3 NEW_LINE z1 = 4 NEW_LINE mirror_point ( a , b , c , d , x1 , y1 , z1 ) NEW_LINE
Number of rectangles in a circle of radius R | Function to return the total possible rectangles that can be cut from the circle ; Diameter = 2 * Radius ; Square of diameter which is the square of the maximum length diagonal ; generate all combinations of a and b in the range ( 1 , ( 2 * Radius - 1 ) ) ( Both inclusive ) ; Calculate the Diagonal length of this rectangle ; If this rectangle 's Diagonal Length is less than the Diameter, it is a valid rectangle, thus increment counter ; Radius of the circle
def countRectangles ( radius ) : NEW_LINE INDENT rectangles = 0 NEW_LINE diameter = 2 * radius NEW_LINE diameterSquare = diameter * diameter NEW_LINE for a in range ( 1 , 2 * radius ) : NEW_LINE INDENT for b in range ( 1 , 2 * radius ) : NEW_LINE INDENT diagonalLengthSquare = ( a * a + b * b ) NEW_LINE if ( diagonalLengthSquare <= diameterSquare ) : NEW_LINE INDENT rectangles += 1 NEW_LINE DEDENT DEDENT DEDENT return rectangles NEW_LINE DEDENT radius = 2 NEW_LINE totalRectangles = countRectangles ( radius ) NEW_LINE print ( totalRectangles , " rectangles ▁ can ▁ be " , " cut ▁ from ▁ a ▁ circle ▁ of ▁ Radius " , radius ) NEW_LINE
Program to check similarity of given two triangles | Function for AAA similarity ; Check for AAA ; Function for SAS similarity ; angle b / w two smallest sides is largest . ; since we take angle b / w the sides . ; Function for SSS similarity ; Check for SSS ; Driver Code ; function call for AAA similarity ; function call for SSS similarity ; function call for SAS similarity ; Check if triangles are similar or not
def simi_aaa ( a1 , a2 ) : NEW_LINE INDENT a1 = [ float ( i ) for i in a1 ] NEW_LINE a2 = [ float ( i ) for i in a2 ] NEW_LINE a1 . sort ( ) NEW_LINE a2 . sort ( ) NEW_LINE if a1 [ 0 ] == a2 [ 0 ] and a1 [ 1 ] == a2 [ 1 ] and a1 [ 2 ] == a2 [ 2 ] : NEW_LINE INDENT return 1 NEW_LINE DEDENT return 0 NEW_LINE DEDENT def simi_sas ( s1 , s2 , a1 , a2 ) : NEW_LINE INDENT s1 = [ float ( i ) for i in s1 ] NEW_LINE s2 = [ float ( i ) for i in s2 ] NEW_LINE a1 = [ float ( i ) for i in a1 ] NEW_LINE a2 = [ float ( i ) for i in a2 ] NEW_LINE s1 . sort ( ) NEW_LINE s2 . sort ( ) NEW_LINE a1 . sort ( ) NEW_LINE a2 . sort ( ) NEW_LINE if s1 [ 0 ] / s2 [ 0 ] == s1 [ 1 ] / s2 [ 1 ] : NEW_LINE INDENT if a1 [ 2 ] == a2 [ 2 ] : NEW_LINE INDENT return 1 NEW_LINE DEDENT DEDENT if s1 [ 1 ] / s2 [ 1 ] == s1 [ 2 ] / s2 [ 2 ] : NEW_LINE INDENT if a1 [ 0 ] == a2 [ 0 ] : NEW_LINE INDENT return 1 NEW_LINE DEDENT DEDENT if s1 [ 2 ] / s2 [ 2 ] == s1 [ 0 ] / s2 [ 0 ] : NEW_LINE INDENT if a1 [ 1 ] == a2 [ 1 ] : NEW_LINE INDENT return 1 NEW_LINE DEDENT DEDENT return 0 NEW_LINE DEDENT def simi_sss ( s1 , s2 ) : NEW_LINE INDENT s1 = [ float ( i ) for i in s1 ] NEW_LINE s2 = [ float ( i ) for i in s2 ] NEW_LINE s1 . sort ( ) NEW_LINE s2 . sort ( ) NEW_LINE if ( s1 [ 0 ] / s2 [ 0 ] == s1 [ 1 ] / s2 [ 1 ] and s1 [ 1 ] / s2 [ 1 ] == s1 [ 2 ] / s2 [ 2 ] and s1 [ 2 ] / s2 [ 2 ] == s1 [ 0 ] / s2 [ 0 ] ) : NEW_LINE INDENT return 1 NEW_LINE DEDENT return 0 NEW_LINE DEDENT s1 = [ 2 , 3 , 3 ] NEW_LINE s2 = [ 4 , 6 , 6 ] NEW_LINE a1 = [ 80 , 60 , 40 ] NEW_LINE a2 = [ 40 , 60 , 80 ] NEW_LINE aaa = simi_aaa ( a1 , a2 ) NEW_LINE sss = simi_sss ( s1 , s2 ) NEW_LINE sas = simi_sas ( s1 , s2 , a1 , a2 ) NEW_LINE if aaa or sss or sas : NEW_LINE INDENT print " Triangles ▁ are ▁ similar ▁ by " , NEW_LINE if aaa : print " AAA " , NEW_LINE if sss : print " SSS " , NEW_LINE if sas : print " SAS " NEW_LINE DEDENT else : print " Triangles ▁ are ▁ not ▁ similar " NEW_LINE
Centered Pentadecagonal Number | centered pentadecagonal function ; Formula to calculate nth centered pentadecagonal number ; Driver Code
def center_pentadecagonal_num ( n ) : NEW_LINE INDENT return ( 15 * n * n - 15 * n + 2 ) // 2 NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT n = 3 NEW_LINE print ( n , " rd ▁ number ▁ : ▁ " , center_pentadecagonal_num ( n ) ) NEW_LINE n = 10 NEW_LINE print ( n , " th ▁ number ▁ : ▁ " , center_pentadecagonal_num ( n ) ) NEW_LINE DEDENT
Centered nonadecagonal number | centered nonadecagonal function ; Formula to calculate nth centered nonadecagonal number & return it into main function . ; Driver Code
def center_nonadecagon_num ( n ) : NEW_LINE INDENT return ( 19 * n * n - 19 * n + 2 ) // 2 NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT n = 2 NEW_LINE print ( n , " nd ▁ centered ▁ nonadecagonal ▁ " + " number ▁ : ▁ " , center_nonadecagon_num ( n ) ) NEW_LINE n = 7 NEW_LINE print ( n , " nd ▁ centered ▁ nonadecagonal ▁ " + " number ▁ : ▁ " , center_nonadecagon_num ( n ) ) NEW_LINE DEDENT
Hendecagonal number | Function of Hendecagonal number ; Formula to calculate nth Hendecagonal number & return it into main function . ; Driver Code
def hendecagonal_num ( n ) : NEW_LINE INDENT return ( 9 * n * n - 7 * n ) // 2 NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT n = 3 NEW_LINE print ( n , " rd ▁ Hendecagonal ▁ number ▁ : ▁ " , hendecagonal_num ( n ) ) NEW_LINE n = 10 NEW_LINE print ( n , " th ▁ Hendecagonal ▁ number ▁ : ▁ " , hendecagonal_num ( n ) ) NEW_LINE DEDENT
Centered Octagonal Number | Function to find centered octagonal number ; Formula to calculate nth centered octagonal number ; Driver Code
def cen_octagonalnum ( n ) : NEW_LINE INDENT return ( 4 * n * n - 4 * n + 1 ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT n = 6 NEW_LINE print ( n , " th ▁ Centered " , " octagonal ▁ number : ▁ " , cen_octagonalnum ( n ) ) NEW_LINE n = 11 NEW_LINE print ( n , " th ▁ Centered " , " octagonal ▁ number : ▁ " , cen_octagonalnum ( n ) ) NEW_LINE DEDENT
Number of ordered points pair satisfying line equation | Checks if ( i , j ) is valid , a point ( i , j ) is valid if point ( arr [ i ] , arr [ j ] ) satisfies the equation y = mx + c And i is not equal to j ; check if i equals to j ; Equation LHS = y , and RHS = mx + c ; Returns the number of ordered pairs ( i , j ) for which point ( arr [ i ] , arr [ j ] ) satisfies the equation of the line y = mx + c ; for every possible ( i , j ) check if ( a [ i ] , a [ j ] ) satisfies the equation y = mx + c ; ( firstIndex , secondIndex ) is same as ( i , j ) ; check if ( firstIndex , secondIndex ) is a valid point ; Driver Code ; equation of line is y = mx + c
def isValid ( arr , i , j , m , c ) : NEW_LINE INDENT if ( i == j ) : NEW_LINE INDENT return False NEW_LINE DEDENT lhs = arr [ j ] ; NEW_LINE rhs = m * arr [ i ] + c NEW_LINE return ( lhs == rhs ) NEW_LINE DEDENT def findOrderedPoints ( arr , n , m , c ) : NEW_LINE INDENT counter = 0 NEW_LINE for i in range ( 0 , n ) : NEW_LINE INDENT for j in range ( 0 , n ) : NEW_LINE INDENT firstIndex = i NEW_LINE secondIndex = j NEW_LINE if ( isValid ( arr , firstIndex , secondIndex , m , c ) ) : NEW_LINE INDENT counter = counter + 1 NEW_LINE DEDENT DEDENT DEDENT return counter NEW_LINE DEDENT arr = [ 1 , 2 , 3 , 4 , 2 ] NEW_LINE n = len ( arr ) NEW_LINE m = 1 NEW_LINE c = 1 NEW_LINE print ( findOrderedPoints ( arr , n , m , c ) ) NEW_LINE
Check if a given circle lies completely inside the ring formed by two concentric circles | Python3 code to check if a circle lies in the ring ; Function to check if circle lies in the ring ; distance between center of circle center of concentric circles ( origin ) using Pythagoras theorem ; Condition to check if circle is strictly inside the ring ; Both circle with radius ' r ' and ' R ' have center ( 0 , 0 )
import math NEW_LINE def checkcircle ( r , R , r1 , x1 , y1 ) : NEW_LINE INDENT dis = int ( math . sqrt ( x1 * x1 + y1 * y1 ) ) NEW_LINE return ( dis - r1 >= R and dis + r1 <= r ) NEW_LINE DEDENT r = 8 ; R = 4 ; r1 = 2 ; x1 = 6 ; y1 = 0 NEW_LINE if ( checkcircle ( r , R , r1 , x1 , y1 ) ) : NEW_LINE INDENT print ( " yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " no " ) NEW_LINE DEDENT
Program for Surface Area of Octahedron | Python Program to calculate surface area of Octahedron . ; utility Function ; driver code
import math NEW_LINE def surface_area_octahedron ( side ) : NEW_LINE INDENT return ( 2 * ( math . sqrt ( 3 ) ) * ( side * side ) ) NEW_LINE DEDENT side = 7 NEW_LINE print ( " Surface ▁ area ▁ of ▁ octahedron ▁ = " , surface_area_octahedron ( side ) ) NEW_LINE
Count of different straight lines with total n points with m collinear | Returns value of binomial coefficient Code taken from https : goo . gl / vhy4jp ; C [ 0 ] = 1 nC0 is 1 ; Compute next row of pascal triangle using the previous row ; function to calculate number of straight lines can be formed ; Driven code
def nCk ( n , k ) : NEW_LINE INDENT C = [ 0 ] * ( k + 1 ) NEW_LINE for i in range ( 1 , n + 1 ) : NEW_LINE INDENT j = min ( i , k ) NEW_LINE while ( j > 0 ) : NEW_LINE INDENT C [ j ] = C [ j ] + C [ j - 1 ] NEW_LINE j = j - 1 NEW_LINE DEDENT DEDENT return C [ k ] NEW_LINE DEDENT def count_Straightlines ( n , m ) : NEW_LINE INDENT return ( nCk ( n , 2 ) - nCk ( m , 2 ) + 1 ) NEW_LINE DEDENT n = 4 NEW_LINE m = 3 NEW_LINE print ( count_Straightlines ( n , m ) ) ; NEW_LINE
Calculate Volume of Dodecahedron | Python3 program to calculate Volume of dodecahedron ; utility Function ; Driver Function
import math NEW_LINE def vol_of_dodecahedron ( side ) : NEW_LINE INDENT return ( ( ( 15 + ( 7 * ( math . sqrt ( 5 ) ) ) ) / 4 ) * ( math . pow ( side , 3 ) ) ) NEW_LINE DEDENT side = 4 NEW_LINE print ( " Volume ▁ of ▁ dodecahedron ▁ = " , round ( vol_of_dodecahedron ( side ) , 2 ) ) NEW_LINE
Program to check if water tank overflows when n solid balls are dipped in the water tank | function to find if tak will overflow or not ; cylinder capacity ; volume of water in tank ; volume of n balls ; total volume of water and n dipped balls ; condition to check if tank is in overflow state or not ; giving dimensions ; calling function
def overflow ( H , r , h , N , R ) : NEW_LINE INDENT tank_cap = 3.14 * r * r * H NEW_LINE water_vol = 3.14 * r * r * h NEW_LINE balls_vol = N * ( 4 / 3 ) * 3.14 * R * R * R NEW_LINE vol = water_vol + balls_vol NEW_LINE if vol > tank_cap : NEW_LINE INDENT print ( " Overflow " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " Not ▁ in ▁ overflow ▁ state " ) NEW_LINE DEDENT DEDENT H = 10 NEW_LINE r = 5 NEW_LINE h = 5 NEW_LINE N = 2 NEW_LINE R = 2 NEW_LINE overflow ( H , r , h , N , R ) NEW_LINE
Program to check if tank will overflow , underflow or filled in given time | function to calculate the volume of tank ; function to print overflow / filled / underflow accordingly ; radius of the tank ; height of the tank ; rate of flow of water ; time given ; calculate the required time ; printing the result
def volume ( radius , height ) : NEW_LINE INDENT return ( ( 22 / 7 ) * radius * radius * height ) NEW_LINE DEDENT def check_and_print ( required_time , given_time ) : NEW_LINE INDENT if required_time < given_time : NEW_LINE INDENT print ( " Overflow " ) NEW_LINE DEDENT elif required_time > given_time : NEW_LINE INDENT print ( " Underflow " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " Filled " ) NEW_LINE DEDENT DEDENT radius = 5 NEW_LINE height = 10 NEW_LINE rate_of_flow = 10 NEW_LINE given_time = 70.0 NEW_LINE required_time = volume ( radius , height ) / rate_of_flow NEW_LINE check_and_print ( required_time , given_time ) NEW_LINE
Program to find third side of triangle using law of cosines | Python3 program to find third side of triangle using law of cosines ; Function to calculate cos value of angle c ; Converting degrees to radian ; Maps the sum along the series ; Holds the actual value of sin ( n ) ; Function to find third side ; Driver Code ; function call
import math as mt NEW_LINE def cal_cos ( n ) : NEW_LINE INDENT accuracy = 0.0001 NEW_LINE x1 , denominator , cosx , cosval = 0 , 0 , 0 , 0 NEW_LINE n = n * ( 3.142 / 180.0 ) NEW_LINE x1 = 1 NEW_LINE cosx = x1 NEW_LINE cosval = mt . cos ( n ) NEW_LINE i = 1 NEW_LINE while ( accuracy <= abs ( cosval - cosx ) ) : NEW_LINE INDENT denominator = 2 * i * ( 2 * i - 1 ) NEW_LINE x1 = - x1 * n * n / denominator NEW_LINE cosx = cosx + x1 NEW_LINE i = i + 1 NEW_LINE DEDENT return cosx NEW_LINE DEDENT def third_side ( a , b , c ) : NEW_LINE INDENT angle = cal_cos ( c ) NEW_LINE return mt . sqrt ( ( a * a ) + ( b * b ) - 2 * a * b * angle ) NEW_LINE DEDENT c = 49 NEW_LINE a , b = 5 , 8 NEW_LINE print ( third_side ( a , b , c ) ) NEW_LINE
Check whether given circle resides in boundary maintained by two other circles | Python3 program to check whether circle with given co - ordinates reside within the boundary of outer circle and inner circle ; function to check if given circle fit in boundary or not ; Distance from the center ; Checking the corners of circle ; Radius of outer circle and inner circle respectively ; Co - ordinates and radius of the circle to be checked
import math NEW_LINE def fitOrNotFit ( R , r , x , y , rad ) : NEW_LINE INDENT val = math . sqrt ( math . pow ( x , 2 ) + math . pow ( y , 2 ) ) NEW_LINE if ( val + rad <= R and val - rad >= R - r ) : NEW_LINE INDENT print ( " Fits " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " Doesn ' t ▁ Fit " ) NEW_LINE DEDENT DEDENT R = 8 NEW_LINE r = 4 NEW_LINE x = 5 NEW_LINE y = 3 NEW_LINE rad = 3 NEW_LINE fitOrNotFit ( R , r , x , y , rad ) NEW_LINE
Program to find line passing through 2 Points | Function to find the line given two points ; Driver code
def lineFromPoints ( P , Q ) : 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 if ( b < 0 ) : NEW_LINE INDENT print ( " The ▁ line ▁ passing ▁ through ▁ points ▁ P ▁ and ▁ Q ▁ is : " , a , " x ▁ - ▁ " , b , " y ▁ = ▁ " , c , " " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " The ▁ line ▁ passing ▁ through ▁ points ▁ P ▁ and ▁ Q ▁ is : ▁ " , a , " x ▁ + ▁ " , b , " y ▁ = ▁ " , c , " " ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT P = [ 3 , 2 ] NEW_LINE Q = [ 2 , 6 ] NEW_LINE lineFromPoints ( P , Q ) NEW_LINE DEDENT
Regular polygon using only 1 s in a binary numbered circle | Python3 program to find whether a regular polygon is possible in circle with 1 s as vertices ; method returns true if polygon is possible with ' midpoints ' number of midpoints ; loop for getting first vertex of polygon ; loop over array values at ' midpoints ' distance ; and ( & ) all those values , if even one of them is 0 , val will be 0 ; if val is still 1 and ( N / midpoints ) or ( number of vertices ) are more than two ( for a polygon minimum ) print result and return true ; method prints sides in the polygon or print not possible in case of no possible polygon ; limit for iterating over divisors ; If i divides N then i and ( N / i ) will be divisors ; check polygon for both divisors ; Driver code
from math import sqrt NEW_LINE def checkPolygonWithMidpoints ( arr , N , midpoints ) : NEW_LINE INDENT for j in range ( midpoints ) : NEW_LINE INDENT val = 1 NEW_LINE for k in range ( j , N , midpoints ) : NEW_LINE INDENT val &= arr [ k ] NEW_LINE DEDENT if ( val and N // midpoints > 2 ) : NEW_LINE INDENT print ( " Polygon ▁ possible ▁ with ▁ side ▁ length " , ( N // midpoints ) ) NEW_LINE return True NEW_LINE DEDENT DEDENT return False NEW_LINE DEDENT def isPolygonPossible ( arr , N ) : NEW_LINE INDENT limit = sqrt ( N ) NEW_LINE for i in range ( 1 , int ( limit ) + 1 ) : NEW_LINE INDENT if ( N % i == 0 ) : NEW_LINE INDENT if ( checkPolygonWithMidpoints ( arr , N , i ) or checkPolygonWithMidpoints ( arr , N , ( N // i ) ) ) : NEW_LINE INDENT return NEW_LINE DEDENT DEDENT DEDENT print ( " Not ▁ possiblen " ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 1 , 0 , 1 , 0 , 1 , 0 , 1 , 0 , 1 , 1 ] NEW_LINE N = len ( arr ) NEW_LINE isPolygonPossible ( arr , N ) NEW_LINE DEDENT
Minimum lines to cover all points | Utility method to get gcd of a and b ; method returns reduced form of dy / dx as a pair ; get sign of result ; method returns minimum number of lines to cover all points where all lines goes through ( xO , yO ) ; set to store slope as a pair ; loop over all points once ; get x and y co - ordinate of current point ; if this slope is not there in set , increase ans by 1 and insert in set ; Driver code
def gcd ( a , b ) : NEW_LINE INDENT if ( b == 0 ) : NEW_LINE INDENT return a NEW_LINE DEDENT return gcd ( b , a % b ) NEW_LINE DEDENT def getReducedForm ( dy , dx ) : NEW_LINE INDENT g = gcd ( abs ( dy ) , abs ( dx ) ) NEW_LINE sign = ( dy < 0 ) ^ ( dx < 0 ) NEW_LINE if ( sign ) : NEW_LINE INDENT return ( - abs ( dy ) // g , abs ( dx ) // g ) NEW_LINE DEDENT else : NEW_LINE INDENT return ( abs ( dy ) // g , abs ( dx ) // g ) NEW_LINE DEDENT DEDENT def minLinesToCoverPoints ( points , N , xO , yO ) : NEW_LINE INDENT st = dict ( ) NEW_LINE minLines = 0 NEW_LINE for i in range ( N ) : NEW_LINE INDENT curX = points [ i ] [ 0 ] NEW_LINE curY = points [ i ] [ 1 ] NEW_LINE temp = getReducedForm ( curY - yO , curX - xO ) NEW_LINE if ( temp not in st ) : NEW_LINE INDENT st [ temp ] = 1 NEW_LINE minLines += 1 NEW_LINE DEDENT DEDENT return minLines NEW_LINE DEDENT xO = 1 NEW_LINE yO = 0 NEW_LINE points = [ [ - 1 , 3 ] , [ 4 , 3 ] , [ 2 , 1 ] , [ - 1 , - 2 ] , [ 3 , - 3 ] ] NEW_LINE N = len ( points ) NEW_LINE print ( minLinesToCoverPoints ( points , N , xO , yO ) ) NEW_LINE
Maximum height when coins are arranged in a triangle | Returns the square root of n . Note that the function ; We are using n itself as initial approximation This can definitely be improved ; e = 0.000001 e decides the accuracy level ; Method to find maximum height of arrangement of coins ; calculating portion inside the square root ; Driver code to test above method
def squareRoot ( n ) : NEW_LINE INDENT x = n NEW_LINE y = 1 NEW_LINE while ( x - y > e ) : NEW_LINE INDENT x = ( x + y ) / 2 NEW_LINE y = n / x NEW_LINE DEDENT return x NEW_LINE DEDENT def findMaximumHeight ( N ) : NEW_LINE INDENT n = 1 + 8 * N NEW_LINE maxH = ( - 1 + squareRoot ( n ) ) / 2 NEW_LINE return int ( maxH ) NEW_LINE DEDENT N = 12 NEW_LINE print ( findMaximumHeight ( N ) ) NEW_LINE
Number of Integral Points between Two Points | Class to represent an Integral point on XY plane . ; Utility function to find GCD of two numbers GCD of a and b ; Finds the no . of Integral points between two given points . ; If line joining p and q is parallel to x axis , then count is difference of y values ; If line joining p and q is parallel to y axis , then count is difference of x values ; Driver Code
class Point : NEW_LINE INDENT def __init__ ( self , a , b ) : NEW_LINE INDENT self . x = a NEW_LINE self . y = b NEW_LINE DEDENT DEDENT def gcd ( a , b ) : NEW_LINE INDENT if b == 0 : NEW_LINE INDENT return a NEW_LINE DEDENT return gcd ( b , a % b ) NEW_LINE DEDENT def getCount ( p , q ) : NEW_LINE INDENT if p . x == q . x : NEW_LINE INDENT return abs ( p . y - q . y ) - 1 NEW_LINE DEDENT if p . y == q . y : NEW_LINE INDENT return abs ( p . x - q . x ) - 1 NEW_LINE DEDENT return gcd ( abs ( p . x - q . x ) , abs ( p . y - q . y ) ) - 1 NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT p = Point ( 1 , 9 ) NEW_LINE q = Point ( 8 , 16 ) NEW_LINE print ( " The ▁ number ▁ of ▁ integral ▁ points " , " between ▁ ( { } , ▁ { } ) ▁ and ▁ ( { } , ▁ { } ) ▁ is ▁ { } " . format ( p . x , p . y , q . x , q . y , getCount ( p , q ) ) ) NEW_LINE DEDENT
How to check if given four points form a square | A Python3 program to check if four given points form a square or not . ; Structure of a point in 2D space ; A utility function to find square of distance from point ' p ' to point 'q ; This function returns true if ( p1 , p2 , p3 , p4 ) form a square , otherwise false ; d2 = distSq ( p1 , p2 ) from p1 to p2 d3 = distSq ( p1 , p3 ) from p1 to p3 d4 = distSq ( p1 , p4 ) from p1 to p4 ; If lengths if ( p1 , p2 ) and ( p1 , p3 ) are same , then following conditions must be met to form a square . 1 ) Square of length of ( p1 , p4 ) is same as twice the square of ( p1 , p2 ) 2 ) Square of length of ( p2 , p3 ) is same as twice the square of ( p2 , p4 ) ; The below two cases are similar to above case ; Driver Code
class Point : NEW_LINE INDENT def __init__ ( self , x , y ) : NEW_LINE INDENT self . x = x NEW_LINE self . y = y NEW_LINE DEDENT DEDENT ' NEW_LINE def distSq ( p , q ) : NEW_LINE INDENT return ( p . x - q . x ) * ( p . x - q . x ) + ( p . y - q . y ) * ( p . y - q . y ) NEW_LINE DEDENT def isSquare ( p1 , p2 , p3 , p4 ) : NEW_LINE INDENT if d2 == 0 or d3 == 0 or d4 == 0 : NEW_LINE INDENT return False NEW_LINE DEDENT if d2 == d3 and 2 * d2 == d4 and 2 * distSq ( p2 , p4 ) == distSq ( p2 , p3 ) : NEW_LINE INDENT return True NEW_LINE DEDENT if d3 == d4 and 2 * d3 == d2 and 2 * distSq ( p3 , p2 ) == distSq ( p3 , p4 ) : NEW_LINE INDENT return True NEW_LINE DEDENT if d2 == d4 and 2 * d2 == d3 and 2 * distSq ( p2 , p3 ) == distSq ( p2 , p4 ) : NEW_LINE INDENT return True NEW_LINE DEDENT return False NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT p1 = Point ( 20 , 10 ) NEW_LINE p2 = Point ( 10 , 20 ) NEW_LINE p3 = Point ( 20 , 20 ) NEW_LINE p4 = Point ( 10 , 10 ) NEW_LINE if isSquare ( p1 , p2 , p3 , p4 ) : NEW_LINE INDENT print ( ' Yes ' ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( ' No ' ) NEW_LINE DEDENT DEDENT
Count triplets such that product of two numbers added with third number is N | Python program for the above approach ; function to find the divisors of the number ( N - i ) ; Stores the resultant count of divisors of ( N - i ) ; Iterate over range [ 1 , sqrt ( N ) ] ; Return the total divisors ; def to find the number of triplets such that A * B - C = N ; Loop to fix the value of C ; Adding the number of divisors in count ; Return count of triplets ; Driver Code Driver Code
import math NEW_LINE def countDivisors ( n ) : NEW_LINE INDENT divisors = 0 NEW_LINE for i in range ( 1 , math . ceil ( math . sqrt ( n ) ) + 1 ) : NEW_LINE INDENT if n % i == 0 : NEW_LINE INDENT divisors = divisors + 1 NEW_LINE DEDENT if ( i - ( n / i ) == 1 ) : NEW_LINE INDENT i = i - 1 NEW_LINE DEDENT DEDENT for i in range ( math . ceil ( math . sqrt ( n ) ) + 1 , 1 , - 1 ) : NEW_LINE INDENT if ( n % i == 0 ) : NEW_LINE INDENT divisors = divisors + 1 NEW_LINE DEDENT DEDENT return divisors NEW_LINE DEDENT def possibleTriplets ( N ) : NEW_LINE INDENT count = 0 NEW_LINE for i in range ( 1 , N ) : NEW_LINE INDENT count = count + countDivisors ( N - i ) NEW_LINE DEDENT return count NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT N = 10 NEW_LINE print ( possibleTriplets ( N ) ) NEW_LINE DEDENT
Maximize count of planes that can be stopped per second with help of given initial position and speed | Function to find maximum number of planes that can be stopped from landing ; Stores the times needed for landing for each plane ; Iterate over the arrays ; Stores the time needed for landing of current plane ; Update the value of t ; Append the t in set St ; Return the answer ; Driver Code
def maxPlanes ( A , B , N ) : NEW_LINE INDENT St = set ( ) NEW_LINE for i in range ( N ) : NEW_LINE INDENT t = 1 if ( A [ i ] % B [ i ] > 0 ) else 0 NEW_LINE t += ( A [ i ] // B [ i ] ) + t NEW_LINE St . add ( t ) NEW_LINE DEDENT return len ( St ) NEW_LINE DEDENT A = [ 1 , 3 , 5 , 4 , 8 ] NEW_LINE B = [ 1 , 2 , 2 , 1 , 2 ] NEW_LINE N = len ( A ) NEW_LINE print ( maxPlanes ( A , B , N ) ) NEW_LINE
Find the player who will win by choosing a number in range [ 1 , K ] with sum total N | Function to predict the winner ; Driver Code ; Given Input ; Function call
def predictTheWinner ( K , N ) : NEW_LINE INDENT if ( N % ( K + 1 ) == 0 ) : NEW_LINE INDENT print ( " Bob " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " Alice " ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT K = 7 NEW_LINE N = 50 NEW_LINE predictTheWinner ( K , N ) NEW_LINE DEDENT
Maximize the rightmost element of an array in k operations in Linear Time | Function to calculate maximum value of Rightmost element ; Initializing ans to store Maximum valued rightmost element ; Calculating maximum value of Rightmost element ; Printing rightmost element ; Driver Code ; Given Input ; Function Call
def maxRightmostElement ( N , k , arr ) : NEW_LINE INDENT ans = arr [ N - 1 ] NEW_LINE i = N - 2 NEW_LINE while ( i >= 0 ) : NEW_LINE INDENT d = min ( arr [ i ] // 2 , k // ( N - 1 - i ) ) NEW_LINE k -= d * ( N - 1 - i ) NEW_LINE ans += d * 2 NEW_LINE i -= 1 NEW_LINE DEDENT print ( ans , end = " ▁ " ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 4 NEW_LINE k = 5 NEW_LINE arr = [ 3 , 8 , 1 , 4 ] NEW_LINE maxRightmostElement ( N , k , arr ) NEW_LINE DEDENT
Minimize the maximum element in constructed Array with sum divisible by K | Function to find smallest maximum number in an array whose sum is divisible by K . ; Minimum possible sum possible for an array of size N such that its sum is divisible by K ; If sum is not divisible by N ; If sum is divisible by N ; Driver code .
def smallestMaximum ( N , K ) : NEW_LINE INDENT sum = ( ( N + K - 1 ) // K ) * K NEW_LINE if ( sum % N != 0 ) : NEW_LINE INDENT return ( sum // N ) + 1 NEW_LINE DEDENT else : NEW_LINE INDENT return sum // N NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT N = 4 NEW_LINE K = 3 NEW_LINE print ( smallestMaximum ( N , K ) ) NEW_LINE DEDENT
Check if it is possible to construct an Array of size N having sum as S and XOR value as X | Function to find if any sequence is possible or not . ; Since , S is greater than equal to X , and either both are odd or even There always exists a sequence ; Only one case possible is S == X or NOT ; Considering the above conditions true , check if XOR of S ^ ( S - X ) is X or not ; Driver Code
def findIfPossible ( N , S , X ) : NEW_LINE INDENT if ( S >= X and S % 2 == X % 2 ) : NEW_LINE INDENT if ( N >= 3 ) : NEW_LINE INDENT return " Yes " NEW_LINE DEDENT if ( N == 1 ) : NEW_LINE INDENT if ( S == X ) : NEW_LINE INDENT return " Yes " NEW_LINE DEDENT else : NEW_LINE INDENT return " No " NEW_LINE DEDENT DEDENT if ( N == 2 ) : NEW_LINE INDENT C = ( S - X ) // 2 NEW_LINE A = C NEW_LINE B = C NEW_LINE A = A + X NEW_LINE if ( ( ( A ^ B ) == X ) ) : NEW_LINE INDENT return " Yes " NEW_LINE DEDENT else : NEW_LINE INDENT return " No " NEW_LINE DEDENT DEDENT DEDENT else : NEW_LINE INDENT return " No " NEW_LINE DEDENT DEDENT N = 3 NEW_LINE S = 10 NEW_LINE X = 4 NEW_LINE print ( findIfPossible ( N , S , X ) ) NEW_LINE
Check whether each Array element can be reduced to minimum element by replacing it with remainder with some X | Python 3 program for the above approach ; Function to check if every integer in the array can be reduced to the minimum array element ; Stores the minimum array element ; Find the minimum element ; Traverse the array arr [ ] ; Stores the maximum value in the range ; Check whether mini lies in the range or not ; Otherwise , return Yes ; Driver Code
import sys NEW_LINE def isPossible ( arr , n ) : NEW_LINE INDENT mini = sys . maxsize NEW_LINE for i in range ( n ) : NEW_LINE INDENT mini = min ( mini , arr [ i ] ) NEW_LINE DEDENT for i in range ( n ) : NEW_LINE INDENT if ( arr [ i ] == mini ) : NEW_LINE INDENT continue NEW_LINE DEDENT Max = ( arr [ i ] + 1 ) // 2 - 1 NEW_LINE if ( mini < 0 or mini > Max ) : NEW_LINE INDENT return " No " NEW_LINE DEDENT DEDENT return " Yes " NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 1 , 1 , 3 , 4 ] NEW_LINE N = len ( arr ) NEW_LINE print ( isPossible ( arr , N ) ) NEW_LINE DEDENT
Maximum number which can divide all array element after one replacement | Function to return gcd1 of two numbers ; If one of numbers is 0 then gcd1 is other number ; If both are equal then that value is gcd1 ; One is greater ; Function to return minimum sum ; Initialize min_sum with large value ; Initialize variable gcd1 ; Storing value of arr [ i ] in c ; Update maxgcd1 if gcd1 is greater than maxgcd1 ; returning the maximum divisor of all elements ; Driver code
def gcd1OfTwoNos ( num1 , num2 ) : NEW_LINE INDENT if ( num1 == 0 ) : NEW_LINE INDENT return num2 NEW_LINE DEDENT if ( num2 == 0 ) : NEW_LINE INDENT return num1 NEW_LINE DEDENT if ( num1 == num2 ) : NEW_LINE INDENT return num1 NEW_LINE DEDENT if ( num1 > num2 ) : NEW_LINE INDENT return gcd1OfTwoNos ( num1 - num2 , num2 ) NEW_LINE DEDENT return gcd1OfTwoNos ( num1 , num2 - num1 ) NEW_LINE DEDENT def Min_sum ( arr , N ) : NEW_LINE INDENT min_sum = 1000000 NEW_LINE maxgcd1 = 1 NEW_LINE for i in range ( N ) : NEW_LINE INDENT gcd1 = 1 NEW_LINE if ( i == 0 ) : NEW_LINE INDENT gcd1 = arr [ 1 ] NEW_LINE DEDENT else : NEW_LINE INDENT gcd1 = arr [ i - 1 ] NEW_LINE DEDENT for j in range ( N ) : NEW_LINE INDENT if ( j != i ) : NEW_LINE INDENT gcd1 = gcd1OfTwoNos ( gcd1 , arr [ j ] ) NEW_LINE DEDENT DEDENT c = arr [ i ] NEW_LINE if ( gcd1 > maxgcd1 ) : NEW_LINE INDENT maxgcd1 = gcd1 NEW_LINE DEDENT DEDENT return maxgcd1 NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 16 , 5 , 10 , 25 ] NEW_LINE N = len ( arr ) NEW_LINE print ( Min_sum ( arr , N ) ) NEW_LINE DEDENT
Count of distinct N | Python Program for the above approach ; Function to find the count of distinct odd integers with N digits using the given digits in the array arr [ ] ; Stores the factorial of a number Calculate the factorial of all numbers from 1 to N ; Stores the frequency of each digit ; Stores the final answer ; Loop to iterate over all values of Nth digit i and 1 st digit j ; If digit i does not exist in the given array move to next i ; Fixing i as Nth digit ; Stores the answer of a specific value of i and j ; If digit j does not exist move to the next j ; Fixing j as 1 st digit ; Calculate number of ways to arrange remaining N - 2 digits ; Including j back into the set of digits ; Including i back into the set of the digits ; Return Answer ; Driver Code ; Function Call
from array import * NEW_LINE from math import * NEW_LINE def countOddIntegers ( arr , N ) : NEW_LINE INDENT Fact = [ 0 ] * N NEW_LINE Fact [ 0 ] = 1 NEW_LINE for i in range ( 1 , N ) : NEW_LINE INDENT Fact [ i ] = i * Fact [ i - 1 ] NEW_LINE DEDENT freq = [ 0 ] * 10 NEW_LINE for i in range ( len ( freq ) ) : NEW_LINE INDENT freq [ i ] = 0 ; NEW_LINE DEDENT for i in range ( N ) : NEW_LINE INDENT freq [ arr [ i ] ] = freq [ arr [ i ] ] + 1 ; NEW_LINE DEDENT ans = 0 NEW_LINE for i in range ( 1 , 10 , 2 ) : NEW_LINE INDENT if ( freq [ i ] == 0 ) : NEW_LINE INDENT continue NEW_LINE DEDENT freq [ i ] = freq [ i ] - 1 ; NEW_LINE for j in range ( 1 , 10 , 1 ) : NEW_LINE INDENT cur_ans = 0 NEW_LINE if ( freq [ j ] == 0 ) : NEW_LINE INDENT continue NEW_LINE DEDENT freq [ j ] = freq [ j ] - 1 ; NEW_LINE cur_ans = Fact [ N - 2 ] NEW_LINE for k in range ( 10 ) : NEW_LINE INDENT cur_ans = cur_ans / Fact [ freq [ k ] ] NEW_LINE DEDENT ans += cur_ans NEW_LINE freq [ j ] = freq [ j ] + 1 ; NEW_LINE DEDENT freq [ i ] = freq [ i ] + 1 ; NEW_LINE DEDENT return ceil ( ans ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT A = [ 2 , 3 , 4 , 1 , 2 , 3 ] NEW_LINE N = len ( A ) NEW_LINE print ( countOddIntegers ( A , N ) ) NEW_LINE DEDENT
Count pairs in an array having sum of elements with their respective sum of digits equal | Function to find the sum of digits of the number N ; Stores the sum of digits ; If the number N is greater than 0 ; Return the sum ; Function to find the count of pairs such that arr [ i ] + sumOfDigits ( arr [ i ] ) is equal to ( arr [ j ] + sumOfDigits ( arr [ j ] ) ; Stores the frequency of value of arr [ i ] + sumOfDigits ( arr [ i ] ) ; Traverse the given array ; Find the value ; Increment the frequency ; Stores the total count of pairs ; Traverse the map mp ; Update the count of pairs ; Return the total count of pairs ; Driver Code
def sumOfDigits ( N ) : NEW_LINE INDENT sum = 0 NEW_LINE while ( N ) : NEW_LINE INDENT sum += ( N % 10 ) NEW_LINE N = N // 10 NEW_LINE DEDENT return sum NEW_LINE DEDENT def CountPair ( arr , n ) : NEW_LINE INDENT mp = { } NEW_LINE for i in range ( n ) : NEW_LINE INDENT val = arr [ i ] + sumOfDigits ( arr [ i ] ) NEW_LINE if val in mp : NEW_LINE INDENT mp [ val ] += 1 NEW_LINE DEDENT else : NEW_LINE INDENT mp [ val ] = 1 NEW_LINE DEDENT DEDENT count = 0 NEW_LINE for key , value in mp . items ( ) : NEW_LINE INDENT val = key NEW_LINE times = value NEW_LINE count += ( ( times * ( times - 1 ) ) // 2 ) NEW_LINE DEDENT return count NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 105 , 96 , 20 , 2 , 87 , 96 ] NEW_LINE N = len ( arr ) NEW_LINE print ( CountPair ( arr , N ) ) NEW_LINE DEDENT
Longest subarray with GCD greater than 1 | Function to build the Segment Tree from the given array to process range queries in log ( N ) time ; Termination Condition ; Find the mid value ; Left and Right Recursive Call ; Update the Segment Tree Node ; Function to return the GCD of the elements of the Array from index l to index r ; Base Case ; Find the middle range ; Find the GCD and return ; Function to print maximum length of the subarray having GCD > one ; Stores the Segment Tree ; Function call to build the Segment tree from array [ ] arr ; Store maximum length of subarray ; Starting and ending pointer of the current window ; Case where the GCD of the current window is 1 ; Update the maximum length ; Print answer ; Driver Code
def build_tree ( b , seg_tree , l , r , vertex ) : NEW_LINE INDENT if ( l == r ) : NEW_LINE INDENT seg_tree [ vertex ] = b [ l ] NEW_LINE return NEW_LINE DEDENT mid = int ( ( l + r ) / 2 ) NEW_LINE build_tree ( b , seg_tree , l , mid , 2 * vertex ) NEW_LINE build_tree ( b , seg_tree , mid + 1 , r , 2 * vertex + 1 ) NEW_LINE seg_tree [ vertex ] = __gcd ( seg_tree [ 2 * vertex ] , seg_tree [ 2 * vertex + 1 ] ) NEW_LINE DEDENT def __gcd ( a , b ) : NEW_LINE INDENT if b == 0 : NEW_LINE INDENT return b NEW_LINE DEDENT else : NEW_LINE INDENT return __gcd ( b , a % b ) NEW_LINE DEDENT DEDENT def range_gcd ( seg_tree , v , tl , tr , l , r ) : NEW_LINE INDENT if ( l > r ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT if ( l == tl and r == tr ) : NEW_LINE INDENT return seg_tree [ v ] NEW_LINE DEDENT tm = int ( ( tl + tr ) / 2 ) NEW_LINE return __gcd ( range_gcd ( seg_tree , 2 * v , tl , tm , l , min ( tm , r ) ) , range_gcd ( seg_tree , 2 * v + 1 , tm + 1 , tr , max ( tm + 1 , l ) , r ) ) NEW_LINE DEDENT def maxSubarrayLen ( arr , n ) : NEW_LINE INDENT seg_tree = [ 0 ] * ( 4 * n + 1 ) NEW_LINE build_tree ( arr , seg_tree , 0 , n - 1 , 1 ) NEW_LINE maxLen = 0 NEW_LINE l , r = 0 , 0 NEW_LINE while ( r < n and l < n ) : NEW_LINE INDENT if ( range_gcd ( seg_tree , 1 , 0 , n - 1 , l , r ) == 1 ) : NEW_LINE INDENT l += 1 NEW_LINE DEDENT maxLen = max ( maxLen , r - l - 1 ) NEW_LINE r += 1 NEW_LINE DEDENT print ( maxLen , end = " " ) NEW_LINE DEDENT arr = [ 410 , 52 , 51 , 180 , 222 , 33 , 33 ] NEW_LINE N = len ( arr ) NEW_LINE maxSubarrayLen ( arr , N ) NEW_LINE
Smallest pair of integers with minimum difference whose Bitwise XOR is N | Python3 program for the above approach ; Function to find the numbers A and B whose Bitwise XOR is N and the difference between them is minimum ; Find the MSB of the N ; Find the value of B ; Find the value of A ; Print the result ; Driver Code
from math import log2 NEW_LINE def findAandB ( N ) : NEW_LINE INDENT K = int ( log2 ( N ) ) NEW_LINE B = ( 1 << K ) NEW_LINE A = B ^ N NEW_LINE print ( A , B ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 26 NEW_LINE findAandB ( N ) NEW_LINE DEDENT
Find all possible values of K such that the sum of first N numbers starting from K is G | Python 3 program for the above approach ; Function to find the count the value of K such that sum of the first N numbers from K is G ; Stores the total count of K ; Iterate till square root of g ; If the number is factor of g ; If the second factor is not equal to first factor ; Check if two factors are odd or not ; If second factor is the same as the first factor then check if the first factor is odd or not ; Print the resultant count ; Driver Code
from math import sqrt NEW_LINE def findValuesOfK ( g ) : NEW_LINE INDENT count = 0 NEW_LINE for i in range ( 1 , int ( sqrt ( g ) ) + 1 , 1 ) : NEW_LINE INDENT if ( g % i == 0 ) : NEW_LINE INDENT if ( i != g // i ) : NEW_LINE INDENT if ( i & 1 ) : NEW_LINE INDENT count += 1 NEW_LINE DEDENT if ( ( g // i ) & 1 ) : NEW_LINE INDENT count += 1 NEW_LINE DEDENT DEDENT elif ( i & 1 ) : NEW_LINE INDENT count += 1 NEW_LINE DEDENT DEDENT DEDENT print ( count ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT G = 125 NEW_LINE findValuesOfK ( G ) NEW_LINE DEDENT
Difference between maximum and minimum average of all K | Function to find the difference between the maximum and minimum subarrays of length K ; Stores the sum of subarray over the range [ 0 , K ] ; Iterate over the range [ 0 , K ] ; Store min and max sum ; Iterate over the range [ K , N - K ] ; Increment sum by arr [ i ] - arr [ i - K ] ; Update max and min moving sum ; Return difference between max and min average ; Driver Code ; Given Input ; Function Call
def Avgdifference ( arr , N , K ) : NEW_LINE INDENT sum = 0 NEW_LINE for i in range ( K ) : NEW_LINE INDENT sum += arr [ i ] NEW_LINE DEDENT min = sum NEW_LINE max = sum NEW_LINE for i in range ( K , N - K + 2 , 1 ) : NEW_LINE INDENT sum += arr [ i ] - arr [ i - K ] NEW_LINE if ( min > sum ) : NEW_LINE INDENT min = sum NEW_LINE DEDENT if ( max < sum ) : NEW_LINE INDENT max = sum NEW_LINE DEDENT DEDENT return ( max - min ) / K NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 3 , 8 , 9 , 15 ] NEW_LINE N = len ( arr ) NEW_LINE K = 2 NEW_LINE print ( Avgdifference ( arr , N , K ) ) NEW_LINE DEDENT
Count of distinct integers in range [ 1 , N ] that do not have any subset sum as K | Function to find maximum number of distinct integers in [ 1 , N ] having no subset with sum equal to K ; Declare a vector to store the required numbers ; Store all the numbers in [ 1 , N ] except K ; Store the maximum number of distinct numbers ; Reverse the array ; Print the required numbers ; Driver Code ; Given Input ; Function Call
def findSet ( N , K ) : NEW_LINE INDENT a = [ ] NEW_LINE for i in range ( 1 , N + 1 ) : NEW_LINE INDENT if ( i != K ) : NEW_LINE INDENT a . append ( i ) NEW_LINE DEDENT DEDENT MaxDistinct = ( N - K ) + ( K // 2 ) NEW_LINE a = a [ : : - 1 ] NEW_LINE for i in range ( MaxDistinct ) : NEW_LINE INDENT print ( a [ i ] , end = " ▁ " ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 5 NEW_LINE K = 3 NEW_LINE findSet ( N , K ) NEW_LINE DEDENT
Solve Linear Congruences Ax = B ( mod N ) for values of x in range [ 0 , N | Function to stores the values of x and y and find the value of gcd ( a , b ) ; Base Case ; Store the result of recursive call ; Update x and y using results of recursive call ; Function to give the distinct solutions of ax = b ( mod n ) ; Function Call to find the value of d and u ; No solution exists ; Else , initialize the value of x0 ; Pr all the answers ; Input ; Function Call
def ExtendedEuclidAlgo ( a , b ) : NEW_LINE INDENT if a == 0 : NEW_LINE INDENT return b , 0 , 1 NEW_LINE DEDENT gcd , x1 , y1 = ExtendedEuclidAlgo ( b % a , a ) NEW_LINE x = y1 - ( b // a ) * x1 NEW_LINE y = x1 NEW_LINE return gcd , x , y NEW_LINE DEDENT def linearCongruence ( A , B , N ) : NEW_LINE INDENT A = A % N NEW_LINE B = B % N NEW_LINE u = 0 NEW_LINE v = 0 NEW_LINE d , u , v = ExtendedEuclidAlgo ( A , N ) NEW_LINE if ( B % d != 0 ) : NEW_LINE INDENT print ( - 1 ) NEW_LINE return NEW_LINE DEDENT x0 = ( u * ( B // d ) ) % N NEW_LINE if ( x0 < 0 ) : NEW_LINE INDENT x0 += N NEW_LINE DEDENT for i in range ( d ) : NEW_LINE INDENT print ( ( x0 + i * ( N // d ) ) % N , end = " ▁ " ) NEW_LINE DEDENT DEDENT A = 15 NEW_LINE B = 9 NEW_LINE N = 18 NEW_LINE linearCongruence ( A , B , N ) NEW_LINE
Factorial of a number without using multiplication | Function to calculate factorial of the number without using multiplication operator ; Variable to store the final factorial ; Outer loop ; Inner loop ; Driver code ; Input ; Function calling
def factorialWithoutMul ( N ) : NEW_LINE INDENT ans = N NEW_LINE i = N - 1 NEW_LINE while ( i > 0 ) : NEW_LINE INDENT sum = 0 NEW_LINE for j in range ( i ) : NEW_LINE INDENT sum += ans NEW_LINE DEDENT ans = sum NEW_LINE i -= 1 NEW_LINE DEDENT return ans NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 5 NEW_LINE print ( factorialWithoutMul ( N ) ) NEW_LINE DEDENT
Sum of Bitwise AND of all unordered triplets of an array | Function to calculate sum of Bitwise AND of all unordered triplets from a given array such that ( i < j < k ) ; Stores the resultant sum of Bitwise AND of all triplets ; Generate all triplets of ( arr [ i ] , arr [ j ] , arr [ k ] ) ; Add Bitwise AND to ans ; Print the result ; Driver Code
def tripletAndSum ( arr , n ) : NEW_LINE INDENT ans = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT for j in range ( i + 1 , n , 1 ) : NEW_LINE INDENT for k in range ( j + 1 , n , 1 ) : NEW_LINE INDENT ans += arr [ i ] & arr [ j ] & arr [ k ] NEW_LINE DEDENT DEDENT DEDENT print ( ans ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 3 , 5 , 4 , 7 ] NEW_LINE N = len ( arr ) NEW_LINE tripletAndSum ( arr , N ) NEW_LINE DEDENT
Sum of Bitwise AND of all unordered triplets of an array | Function to calculate sum of Bitwise AND of all unordered triplets from a given array such that ( i < j < k ) ; Stores the resultant sum of Bitwise AND of all triplets ; Traverse over all the bits ; Count number of elements with the current bit set ; There are ( cnt ) C ( 3 ) numbers with the current bit set and each triplet contributes 2 ^ bit to the result ; Return the resultant sum ; Driver Code
def tripletAndSum ( arr , n ) : NEW_LINE INDENT ans = 0 NEW_LINE for bit in range ( 32 ) : NEW_LINE INDENT cnt = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( arr [ i ] & ( 1 << bit ) ) : NEW_LINE INDENT cnt += 1 NEW_LINE DEDENT DEDENT ans += ( 1 << bit ) * cnt * ( cnt - 1 ) * ( cnt - 2 ) // 6 NEW_LINE DEDENT return ans NEW_LINE DEDENT arr = [ 3 , 5 , 4 , 7 ] NEW_LINE N = len ( arr ) NEW_LINE print ( tripletAndSum ( arr , N ) ) NEW_LINE
Lexicographically smallest permutation of length 2 N that can be obtained from an N | Python3 program for the above approach ; Function to find the lexicographically smallest permutation of length 2 * N satisfying the given conditions ; Stores if i - th element is placed at odd position or not ; Traverse the array ; Mark arr [ i ] true ; Stores all the elements not placed at odd positions ; Iterate in the range [ 1 , 2 * N ] ; If w [ i ] is not marked ; Stores whether it is possible to obtain the required permutation or not ; Stores the permutation ; Traverse the array arr [ ] ; Finds the iterator of the smallest number greater than the arr [ i ] ; If it is S . end ( ) ; Mark found false ; Push arr [ i ] and * it into the array ; Erase the current element from the Set ; If found is not marked ; Otherwise , ; Print the permutation ; Driver Code ; Given Input ; Function call
from bisect import bisect_left NEW_LINE def smallestPermutation ( arr , N ) : NEW_LINE INDENT w = [ False for i in range ( 2 * N + 1 ) ] NEW_LINE for i in range ( N ) : NEW_LINE INDENT w [ arr [ i ] ] = True NEW_LINE DEDENT S = set ( ) NEW_LINE for i in range ( 1 , 2 * N + 1 , 1 ) : NEW_LINE INDENT if ( w [ i ] == False ) : NEW_LINE INDENT S . add ( i ) NEW_LINE DEDENT DEDENT found = True NEW_LINE P = [ ] NEW_LINE S = list ( S ) NEW_LINE for i in range ( N ) : NEW_LINE INDENT it = bisect_left ( S , arr [ i ] ) NEW_LINE if ( it == - 1 ) : NEW_LINE INDENT found = False NEW_LINE break NEW_LINE DEDENT P . append ( arr [ i ] ) NEW_LINE P . append ( S [ it ] ) NEW_LINE S . remove ( S [ it ] ) NEW_LINE DEDENT if ( found == False ) : NEW_LINE INDENT print ( " - 1" ) NEW_LINE DEDENT else : NEW_LINE INDENT for i in range ( 2 * N ) : NEW_LINE INDENT print ( P [ i ] , end = " ▁ " ) NEW_LINE DEDENT DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 4 , 1 , 3 ] NEW_LINE N = len ( arr ) NEW_LINE smallestPermutation ( arr , N ) NEW_LINE DEDENT
Maximum sum of a subsequence having difference between their indices equal to the difference between their values | Function to find the maximum sum of a subsequence having difference between indices equal to difference in their values ; Stores the maximum sum ; Stores the value for each A [ i ] - i ; Traverse the array ; Update the value in map ; Update the answer ; Finally , print the answer ; Driver Code ; Given Input ; Function Call
def maximumSubsequenceSum ( A , N ) : NEW_LINE INDENT ans = 0 NEW_LINE mp = { } NEW_LINE for i in range ( N ) : NEW_LINE INDENT if ( A [ i ] - i in mp ) : NEW_LINE INDENT mp [ A [ i ] - i ] += A [ i ] NEW_LINE DEDENT else : NEW_LINE INDENT mp [ A [ i ] - i ] = A [ i ] NEW_LINE DEDENT ans = max ( ans , mp [ A [ i ] - i ] ) NEW_LINE DEDENT print ( ans ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT A = [ 10 , 7 , 1 , 9 , 10 , 1 ] NEW_LINE N = len ( A ) NEW_LINE maximumSubsequenceSum ( A , N ) NEW_LINE DEDENT
Find the nearest perfect square for each element of the array | Function to find the nearest perfect square for every element in the given array import the math module ; Traverse the array ; Calculate square root of current element ; Calculate perfect square ; Find the nearest ; Driver Code
import math NEW_LINE def nearestPerfectSquare ( arr , N ) : NEW_LINE INDENT for i in range ( 0 , N ) : NEW_LINE INDENT sr = math . floor ( math . sqrt ( arr [ i ] ) ) NEW_LINE a = sr * sr NEW_LINE b = ( sr + 1 ) * ( sr + 1 ) NEW_LINE if ( ( arr [ i ] - a ) < ( b - arr [ i ] ) ) : NEW_LINE print ( a , end = " ▁ " ) NEW_LINE else : NEW_LINE print ( b , end = " ▁ " ) NEW_LINE DEDENT DEDENT arr = [ 5 , 2 , 7 , 13 ] NEW_LINE N = len ( arr ) NEW_LINE nearestPerfectSquare ( arr , N ) NEW_LINE
Count of sets possible using integers from a range [ 2 , N ] using given operations that are in Equivalence Relation | Python3 program for the above approach ; Sieve of Eratosthenes to find primes less than or equal to N ; Function to find number of Sets ; Handle Base Case ; Set which contains less than or equal to N / 2 ; Number greater than N / 2 and are prime increment it by 1 ; If the number is prime Increment answer by 1 ; Driver Code ; Input ; Function Call
prime = [ True ] * 100001 NEW_LINE def SieveOfEratosthenes ( n ) : NEW_LINE INDENT global prime NEW_LINE for p in range ( 2 , n + 1 ) : NEW_LINE INDENT if p * p > n : NEW_LINE INDENT break NEW_LINE DEDENT 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 NumberofSets ( N ) : NEW_LINE INDENT SieveOfEratosthenes ( N ) NEW_LINE if ( N == 2 ) : NEW_LINE INDENT print ( 1 ) NEW_LINE DEDENT elif ( N == 3 ) : NEW_LINE INDENT print ( 2 ) NEW_LINE DEDENT else : NEW_LINE INDENT ans = 1 NEW_LINE for i in range ( N // 2 , N + 1 ) : NEW_LINE INDENT if ( prime [ i ] ) : NEW_LINE INDENT ans += 1 NEW_LINE DEDENT DEDENT print ( ans ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 9 NEW_LINE NumberofSets ( N ) NEW_LINE DEDENT
Absolute difference between floor of Array sum divided by X and floor sum of every Array element when divided by X | Function to find absolute difference between the two sum values ; Variable to store total sum ; Variable to store sum of A [ i ] / X ; Traverse the array ; Update totalSum ; Update perElementSum ; Floor of total sum divided by X ; Return the absolute difference ; Driver Code ; Input ; Size of Array ; Function call to find absolute difference between the two sum values
def floorDifference ( A , N , X ) : NEW_LINE INDENT totalSum = 0 NEW_LINE perElementSum = 0 NEW_LINE for i in range ( N ) : NEW_LINE INDENT totalSum += A [ i ] NEW_LINE perElementSum += A [ i ] // X NEW_LINE DEDENT totalFloorSum = totalSum // X NEW_LINE return abs ( totalFloorSum - perElementSum ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT A = [ 1 , 2 , 3 , 4 , 5 , 6 ] NEW_LINE X = 4 NEW_LINE N = len ( A ) NEW_LINE print ( floorDifference ( A , N , X ) ) NEW_LINE DEDENT
Convert a number from base A to base B | Function to return ASCII value of a character ; Function to convert a number from given base to decimal number ; Stores the length of the string ; Initialize power of base ; Initialize result ; Decimal equivalent is strr [ len - 1 ] * 1 + strr [ len - 2 ] * base + strr [ len - 3 ] * ( base ^ 2 ) + ... ; A digit in input number must be less than number 's base ; Update num ; Update power ; Function to return equivalent character of a given value ; Function to convert a given decimal number to a given base ; Store the result ; Repeatedly divide inputNum by base and take remainder ; Update res ; Update inputNum ; Reverse the result ; Function to convert a given number from a base to another base ; Convert the number from base A to decimal ; Convert the number from decimal to base B ; Prthe result ; Given input ; Function Call
def val ( c ) : NEW_LINE INDENT if ( c >= '0' and c <= '9' ) : NEW_LINE INDENT return ord ( c ) - 48 NEW_LINE DEDENT else : NEW_LINE INDENT return ord ( c ) - 65 + 10 NEW_LINE DEDENT DEDENT def toDeci ( strr , base ) : NEW_LINE INDENT lenn = len ( strr ) NEW_LINE power = 1 NEW_LINE num = 0 NEW_LINE for i in range ( lenn - 1 , - 1 , - 1 ) : NEW_LINE INDENT if ( val ( strr [ i ] ) >= base ) : NEW_LINE INDENT print ( " Invalid ▁ Number " ) NEW_LINE return - 1 NEW_LINE DEDENT num += val ( strr [ i ] ) * power NEW_LINE power = power * base NEW_LINE DEDENT return num NEW_LINE DEDENT def reVal ( num ) : NEW_LINE INDENT if ( num >= 0 and num <= 9 ) : NEW_LINE INDENT return chr ( num + 48 ) NEW_LINE DEDENT else : NEW_LINE INDENT return chr ( num - 10 + 65 ) NEW_LINE DEDENT DEDENT def fromDeci ( base , inputNum ) : NEW_LINE INDENT res = " " NEW_LINE while ( inputNum > 0 ) : NEW_LINE INDENT res += reVal ( inputNum % base ) NEW_LINE inputNum //= base NEW_LINE DEDENT res = res [ : : - 1 ] NEW_LINE return res NEW_LINE DEDENT def convertBase ( s , a , b ) : NEW_LINE INDENT num = toDeci ( s , a ) NEW_LINE ans = fromDeci ( b , num ) NEW_LINE print ( ans ) NEW_LINE DEDENT s = "10B " NEW_LINE a = 16 NEW_LINE b = 10 NEW_LINE convertBase ( s , a , b ) NEW_LINE
Prefix Factorials of a Prefix Sum Array | Function to find the factorial of a number N ; Base Case ; Find the factorial recursively ; Function to find the prefix factorial array ; Find the prefix sum array ; Find the factorials of each array element ; Print the resultant array ; Driver Code
def fact ( N ) : NEW_LINE INDENT if ( N == 1 or N == 0 ) : NEW_LINE INDENT return 1 NEW_LINE DEDENT return N * fact ( N - 1 ) NEW_LINE DEDENT def prefixFactorialArray ( arr , N ) : NEW_LINE INDENT for i in range ( 1 , N ) : NEW_LINE INDENT arr [ i ] += arr [ i - 1 ] NEW_LINE DEDENT for i in range ( N ) : NEW_LINE INDENT arr [ i ] = fact ( arr [ i ] ) 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 arr = [ 1 , 2 , 3 , 4 ] NEW_LINE N = len ( arr ) NEW_LINE prefixFactorialArray ( arr , 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 ; Store the resultant average calculated using formula ; Return the average ; Driver Code
def findAverage ( N ) : NEW_LINE INDENT avg = ( ( 6 * N * N * N * N ) + ( 15 * N * N * N ) + ( 10 * N * N ) - 1 ) / 30 NEW_LINE return avg NEW_LINE DEDENT N = 3 NEW_LINE print ( round ( findAverage ( N ) , 4 ) ) NEW_LINE
Modify array by removing ( arr [ i ] + arr [ i + 1 ] ) th element exactly K times | Function to modify array by removing every K - th element from the array ; Check if current element is the k - th element ; Stores the elements after removing every kth element ; Append the current element if it is not k - th element ; Return the new array after removing every k - th element ; Function to print the array ; Traverse the array l [ ] ; Function to print the array after performing the given operations exactly k times ; Store first N natural numbers ; Iterate over the range [ 0 , k - 1 ] ; Store sums of the two consecutive terms ; Remove every p - th element from the array ; Increment x by 1 for the next iteration ; Print the resultant array ; Given arrays ; Function Call
def removeEveryKth ( l , k ) : NEW_LINE INDENT for i in range ( 0 , len ( l ) ) : NEW_LINE INDENT if i % k == 0 : NEW_LINE INDENT l [ i ] = 0 NEW_LINE DEDENT DEDENT arr = [ 0 ] NEW_LINE for i in range ( 1 , len ( l ) ) : NEW_LINE INDENT if l [ i ] != 0 : NEW_LINE INDENT arr . append ( l [ i ] ) NEW_LINE DEDENT DEDENT return arr NEW_LINE DEDENT def printArray ( l ) : NEW_LINE INDENT for i in range ( 1 , len ( l ) ) : NEW_LINE INDENT print ( l [ i ] , end = " ▁ " ) NEW_LINE DEDENT print ( ) NEW_LINE DEDENT def printSequence ( n , k ) : NEW_LINE INDENT l = [ int ( i ) for i in range ( 0 , n + 1 ) ] NEW_LINE x = 1 NEW_LINE for i in range ( 0 , k ) : NEW_LINE INDENT p = l [ x ] + l [ x + 1 ] NEW_LINE l = removeEveryKth ( l , p ) NEW_LINE x += 1 NEW_LINE DEDENT printArray ( l ) NEW_LINE DEDENT N = 8 NEW_LINE K = 2 NEW_LINE printSequence ( N , K ) NEW_LINE
Minimum number of bits of array elements required to be flipped to make all array elements equal | Function to count minimum number of bits required to be flipped to make all array elements equal ; Stores the count of unset bits ; Stores the count of set bits ; Traverse the array ; Traverse the bit of arr [ i ] ; If current bit is set ; Increment fre1 [ j ] ; Otherwise ; Increment fre0 [ j ] ; Right shift x by 1 ; Stores the count of total moves ; Traverse the range [ 0 , 32 ] ; Update the value of ans ; Return the minimum number of flips required ; Driver Code
def makeEqual ( arr , n ) : NEW_LINE INDENT fre0 = [ 0 ] * 33 NEW_LINE fre1 = [ 0 ] * 33 NEW_LINE for i in range ( n ) : NEW_LINE INDENT x = arr [ i ] NEW_LINE for j in range ( 33 ) : NEW_LINE INDENT if ( x & 1 ) : NEW_LINE INDENT fre1 [ j ] += 1 NEW_LINE DEDENT else : NEW_LINE INDENT fre0 [ j ] += 1 NEW_LINE DEDENT x = x >> 1 NEW_LINE DEDENT DEDENT ans = 0 NEW_LINE for i in range ( 33 ) : NEW_LINE INDENT ans += min ( fre0 [ i ] , fre1 [ i ] ) NEW_LINE DEDENT return ans NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 3 , 5 ] NEW_LINE N = len ( arr ) NEW_LINE print ( makeEqual ( arr , N ) ) NEW_LINE DEDENT
Sum of array elements possible by appending arr [ i ] / K to the end of the array K times for array elements divisible by K | Function to calculate sum of array elements after adding arr [ i ] / K to the end of the array if arr [ i ] is divisible by K ; Stores the sum of the array ; Traverse the array arr [ ] ; Traverse the vector ; If v [ i ] is divisible by K ; Iterate over the range [ 0 , K ] ; Update v ; Otherwise ; Traverse the vector v ; Return the sum of the updated array ; Driver Code
def summ ( arr , N , K ) : NEW_LINE INDENT sum = 4 NEW_LINE v = [ i for i in arr ] NEW_LINE for i in range ( len ( v ) ) : NEW_LINE INDENT if ( v [ i ] % K == 0 ) : NEW_LINE INDENT x = v [ i ] // K NEW_LINE for j in range ( K ) : NEW_LINE INDENT v . append ( x ) NEW_LINE DEDENT DEDENT else : NEW_LINE INDENT break NEW_LINE DEDENT DEDENT for i in range ( len ( v ) ) : NEW_LINE INDENT sum = sum + v [ i ] NEW_LINE DEDENT return sum NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 4 , 6 , 8 , 2 ] NEW_LINE K = 2 NEW_LINE N = len ( arr ) NEW_LINE print ( summ ( arr , N , K ) ) NEW_LINE DEDENT
Check if sum of arr [ i ] / j for all possible pairs ( i , j ) in an array is 0 or not | Function to check if sum of all values of ( arr [ i ] / j ) for all 0 < i <= j < ( N - 1 ) is 0 or not ; Stores the required sum ; Traverse the array ; If the sum is equal to 0 ; Otherwise ; Driver Code
def check ( arr , N ) : NEW_LINE INDENT sum = 0 NEW_LINE for i in range ( N ) : NEW_LINE INDENT sum += arr [ i ] NEW_LINE DEDENT if ( sum == 0 ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 1 , - 1 , 3 , - 2 , - 1 ] NEW_LINE N = len ( arr ) NEW_LINE check ( arr , N ) NEW_LINE DEDENT
Program to calculate expected increase in price P after N consecutive days | Function to find the increased value of P after N days ; Expected value of the number P after N days ; Print the expected value ; Driver Code
def expectedValue ( P , a , b , N ) : NEW_LINE INDENT expValue = P + ( N * 0.5 * ( a + b ) ) NEW_LINE print ( int ( expValue ) ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT P = 3000 NEW_LINE a = 20 NEW_LINE b = 10 NEW_LINE N = 30 NEW_LINE expectedValue ( P , a , b , N ) NEW_LINE DEDENT
Find the index in a circular array from which prefix sum is always non | Function to find the starting index of the given circular array prefix sum array is non negative ; Stores the sum of the array ; Stores the starting index ; Stores the minimum prefix sum of A [ 0. . i ] ; Traverse the array ; Update the value of sum ; If sum is less than minimum ; Update the min as the value of prefix sum ; Update starting index ; Otherwise no such index is possible ; Driver code
import sys NEW_LINE def startingPoint ( A , N ) : NEW_LINE INDENT sum = 0 NEW_LINE startingindex = 0 NEW_LINE min = sys . maxsize NEW_LINE for i in range ( 0 , N ) : NEW_LINE INDENT sum += A [ i ] NEW_LINE if ( sum < min ) : NEW_LINE INDENT min = sum NEW_LINE startingindex = i + 1 NEW_LINE DEDENT DEDENT if ( sum < 0 ) : NEW_LINE INDENT return - 1 NEW_LINE DEDENT return startingindex % N NEW_LINE DEDENT arr = [ 3 , - 6 , 7 , - 4 , - 4 , 6 , - 1 ] NEW_LINE N = len ( arr ) NEW_LINE print ( startingPoint ( arr , N ) ) NEW_LINE
Modify array by replacing elements with the nearest power of its previous or next element | Python3 program for the above approach ; Function to calculate the power of y which is nearest to x ; Base Case ; Stores the logarithmic value of x with base y ; Function to replace each array element by the nearest power of its previous or next element ; Stores the previous and next element ; Traverse the array ; Calculate nearest power for previous and next elements ; Replacing the array values ; Print the updated array ; Given array
import math NEW_LINE def nearestPow ( x , y ) : NEW_LINE INDENT if y == 1 : NEW_LINE INDENT return 1 NEW_LINE DEDENT k = int ( math . log ( x , y ) ) NEW_LINE if abs ( y ** k - x ) < abs ( y ** ( k + 1 ) - x ) : NEW_LINE INDENT return y ** k NEW_LINE DEDENT return y ** ( k + 1 ) NEW_LINE DEDENT def replacebyNearestPower ( arr ) : NEW_LINE INDENT prev = arr [ - 1 ] NEW_LINE lastNext = arr [ 0 ] NEW_LINE for i in range ( len ( arr ) ) : NEW_LINE INDENT temp = arr [ i ] NEW_LINE if i == len ( arr ) - 1 : NEW_LINE INDENT next = lastNext NEW_LINE DEDENT else : NEW_LINE INDENT next = arr [ ( i + 1 ) % len ( arr ) ] NEW_LINE DEDENT prevPow = nearestPow ( arr [ i ] , prev ) NEW_LINE nextPow = nearestPow ( arr [ i ] , next ) NEW_LINE if abs ( arr [ i ] - prevPow ) < abs ( arr [ i ] - nextPow ) : NEW_LINE INDENT arr [ i ] = prevPow NEW_LINE DEDENT else : NEW_LINE INDENT arr [ i ] = nextPow NEW_LINE DEDENT prev = temp NEW_LINE DEDENT print ( arr ) NEW_LINE DEDENT arr = [ 2 , 3 , 4 , 1 , 2 ] NEW_LINE replacebyNearestPower ( arr ) NEW_LINE
Check if sum of array can be made equal to X by removing either the first or last digits of every array element | Utility Function to check if the sum of the array elements can be made equal to X by removing either the first or last digits of every array element ; Base Case ; Convert arr [ i ] to string ; Remove last digit ; Remove first digit ; Recursive function call ; Function to check if sum of given array can be made equal to X or not ; Driver Code ; Function Call
def makeSumX ( arr , X , S , i ) : NEW_LINE INDENT if i == len ( arr ) : NEW_LINE INDENT return S == X NEW_LINE DEDENT a = str ( arr [ i ] ) NEW_LINE l = int ( a [ : - 1 ] ) NEW_LINE r = int ( a [ 1 : ] ) NEW_LINE x = makeSumX ( arr , X , S + l , i + 1 ) NEW_LINE y = makeSumX ( arr , X , S + r , i + 1 ) NEW_LINE return x | y NEW_LINE DEDENT def Check ( arr , X ) : NEW_LINE INDENT if ( makeSumX ( arr , X , 0 , 0 ) ) : NEW_LINE print ( " Yes " ) NEW_LINE else : NEW_LINE print ( " No " ) NEW_LINE DEDENT arr = [ 545 , 433 , 654 , 23 ] NEW_LINE X = 134 NEW_LINE Check ( arr , X ) NEW_LINE
Count subarrays having product equal to the power of a given Prime Number | Python 3 program for the above approach ; Function to check if y is a power of m or not ; Calculate log y base m and store it in a variable with integer datatype ; Calculate log y base m and store it in a variable with double datatype ; If res1 and res2 are equal , return True . Otherwise , return false ; Function to count the number of subarrays having product of elements equal to a power of m , where m is a prime number ; Stores the count of subarrays required ; Stores current sequence of consecutive array elements which are a multiple of m ; Traverse the array ; If arr [ i ] is a power of M ; Increment cnt ; Update ans ; Update cnt ; Return the count of subarrays ; Driver Code ; Input
from math import log NEW_LINE def isPower ( m , y ) : NEW_LINE INDENT res1 = log ( y ) // log ( m ) NEW_LINE res2 = log ( y ) // log ( m ) NEW_LINE return ( res1 == res2 ) NEW_LINE DEDENT def numSub ( arr , n , m ) : NEW_LINE INDENT ans = 0 NEW_LINE cnt = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( isPower ( m , arr [ i ] ) ) : NEW_LINE INDENT cnt += 1 NEW_LINE ans += ( cnt * ( cnt - 1 ) ) // 2 NEW_LINE DEDENT else : NEW_LINE INDENT cnt = 0 NEW_LINE DEDENT DEDENT return ans NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 1 , 1 , 1 , 3 ] NEW_LINE m = 3 NEW_LINE n = len ( arr ) NEW_LINE print ( numSub ( arr , n , m ) ) NEW_LINE DEDENT
Count pairs whose Bitwise AND exceeds Bitwise XOR from a given array | Python3 program to implement the above approach ; Function to count pairs that satisfy the above condition ; Stores the count of pairs ; Stores the count of array elements having same positions of MSB ; Traverse the array ; Stores the index of MSB of array elements ; Calculate number of pairs ; Driver Code ; Given Input ; Function call to count pairs satisfying the given condition
import math NEW_LINE def cntPairs ( arr , N ) : NEW_LINE INDENT res = 0 NEW_LINE bit = [ 0 ] * 32 NEW_LINE for i in range ( N ) : NEW_LINE INDENT pos = ( int ) ( math . log2 ( arr [ i ] ) ) NEW_LINE bit [ pos ] += 1 NEW_LINE DEDENT for i in range ( 32 ) : NEW_LINE INDENT res += ( bit [ i ] * ( bit [ i ] - 1 ) ) // 2 NEW_LINE DEDENT return res NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 1 , 2 , 3 , 4 ] NEW_LINE N = len ( arr ) NEW_LINE print ( cntPairs ( arr , N ) ) NEW_LINE DEDENT
Minimum MEX from all subarrays of length K | Function to return minimum MEX from all K - length subarrays ; Stores element from [ 1 , N + 1 ] which are not present in subarray ; Store number 1 to N + 1 in set s ; Find the MEX of K - length subarray starting from index 0 ; Find the MEX of all subarrays of length K by erasing arr [ i ] and inserting arr [ i - K ] ; Store first element of set ; Updating the mex ; Print minimum MEX of all K length subarray ; Driver Code
def minimumMEX ( arr , N , K ) : NEW_LINE INDENT s = set ( ) NEW_LINE for i in range ( 1 , N + 2 , 1 ) : NEW_LINE INDENT s . add ( i ) NEW_LINE DEDENT for i in range ( K ) : NEW_LINE INDENT s . remove ( arr [ i ] ) NEW_LINE DEDENT mex = list ( s ) [ 0 ] NEW_LINE for i in range ( K , N , 1 ) : NEW_LINE INDENT s . remove ( arr [ i ] ) NEW_LINE s . add ( arr [ i - K ] ) NEW_LINE firstElem = list ( s ) [ 0 ] NEW_LINE mex = min ( mex , firstElem ) NEW_LINE DEDENT print ( mex ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 1 , 2 , 3 , 4 , 5 , 6 ] NEW_LINE K = 3 NEW_LINE N = len ( arr ) NEW_LINE minimumMEX ( arr , N , K ) NEW_LINE DEDENT
Count smaller elements present in the array for each array element | Function to count for each array element , the number of elements that are smaller than that element ; Stores the frequencies of array elements ; Traverse the array ; Update frequency of arr [ i ] ; Initialize sum with 0 ; Compute prefix sum of the array hash [ ] ; Traverse the array arr [ ] ; If current element is 0 ; Print the resultant count ; Driver Code
def smallerNumbers ( arr , N ) : NEW_LINE INDENT hash = [ 0 ] * 100000 NEW_LINE for i in range ( N ) : NEW_LINE INDENT hash [ arr [ i ] ] += 1 NEW_LINE DEDENT sum = 0 NEW_LINE for i in range ( 1 , 100000 ) : NEW_LINE INDENT hash [ i ] += hash [ i - 1 ] NEW_LINE DEDENT for i in range ( N ) : NEW_LINE INDENT if ( arr [ i ] == 0 ) : NEW_LINE INDENT print ( "0" ) NEW_LINE continue NEW_LINE DEDENT print ( hash [ arr [ i ] - 1 ] , end = " ▁ " ) NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 3 , 4 , 1 , 1 , 2 ] NEW_LINE N = len ( arr ) NEW_LINE smallerNumbers ( arr , N ) NEW_LINE DEDENT
Modulo Operations in Programming With Negative Results | Function to calculate and return the remainder of a % n ; ( a / n ) implicitly gives the truncated result ; Driver Code ; Modulo of two positive numbers ; Modulo of a negative number by a positive number ; Modulo of a positive number by a negative number ; Modulo of two negative numbers
def truncMod ( a , n ) : NEW_LINE INDENT q = a // n NEW_LINE return a - n * q NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT a = 9 NEW_LINE b = 4 NEW_LINE print ( a , " % " , b , " = " , truncMod ( a , b ) ) NEW_LINE a = - 9 NEW_LINE b = 4 NEW_LINE print ( a , " % " , b , " = " , truncMod ( a , b ) ) NEW_LINE a = 9 NEW_LINE b = - 4 NEW_LINE print ( a , " % " , b , " = " , truncMod ( a , b ) ) NEW_LINE a = - 9 NEW_LINE b = - 4 NEW_LINE print ( a , " % " , b , " = " , truncMod ( a , b ) ) NEW_LINE DEDENT
Program for average of an array without running into overflow | Python3 program for the above approach ; Function to calculate average of an array using standard method ; Stores the sum of array ; Find the sum of the array ; Return the average ; Function to calculate average of an array using efficient method ; Store the average of the array ; Traverse the array arr [ ] ; Update avg ; Return avg ; Driver Code ; Input ; Function call
import sys NEW_LINE def average ( arr , N ) : NEW_LINE INDENT sum = 0 NEW_LINE for i in range ( N ) : NEW_LINE INDENT sum += arr [ i ] NEW_LINE DEDENT return sum // N * 1.0 - 1 NEW_LINE DEDENT def mean ( arr , N ) : NEW_LINE INDENT avg = 0 NEW_LINE for i in range ( N ) : NEW_LINE INDENT avg += ( arr [ i ] - avg ) / ( i + 1 ) NEW_LINE DEDENT return round ( avg , 7 ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 2147483647 , 1 , 2 ] NEW_LINE N = len ( arr ) NEW_LINE print ( " Average ▁ by ▁ Standard ▁ method : ▁ " , " { : . 10f } " . format ( - 1.0 * average ( arr , N ) ) ) NEW_LINE print ( " Average ▁ by ▁ Efficient ▁ method : ▁ " , " { : . 10f } " . format ( mean ( arr , N ) ) ) NEW_LINE DEDENT
Count number of pairs ( i , j ) from an array such that arr [ i ] * j = arr [ j ] * i | Python3 program for the above approach ; Function to count pairs from an array satisfying given conditions ; Stores the total count of pairs ; Stores count of a [ i ] / i ; Traverse the array ; Updating count ; Update frequency in the Map ; Print count of pairs ; Driver Code ; Given array ; Size of the array ; Function call to count pairs satisfying given conditions
from collections import defaultdict NEW_LINE def countPairs ( arr , N ) : NEW_LINE INDENT count = 0 NEW_LINE mp = defaultdict ( int ) NEW_LINE for i in range ( N ) : NEW_LINE INDENT val = 1.0 * arr [ i ] NEW_LINE idx = 1.0 * ( i + 1 ) NEW_LINE count += mp [ val / idx ] NEW_LINE mp [ val / idx ] += 1 NEW_LINE DEDENT print ( count ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 1 , 3 , 5 , 6 , 5 ] NEW_LINE N = len ( arr ) NEW_LINE countPairs ( arr , N ) NEW_LINE DEDENT
Count ancestors with smaller value for each node of a Binary Tree | Function to add an edge between nodes u and v ; Function to perform the DFS Traversal and store parent of each node ; Store the immediate parent ; Traverse the children of the current node ; Recursively call for function dfs for the child node ; Function to count the number of ancestors with values smaller than that of the current node ; Perform the DFS Traversal ; Traverse all the nodes ; Store the number of ancestors smaller than node ; Loop until parent [ node ] != - 1 ; If the condition satisfies , increment cnt by 1 ; Print the required result for the current node ; Driver Code ; Tree Formation
def add_edge ( u , v ) : NEW_LINE INDENT global adj NEW_LINE adj [ u ] . append ( v ) NEW_LINE adj [ v ] . append ( u ) NEW_LINE DEDENT def dfs ( u , par = - 1 ) : NEW_LINE INDENT global adj , parent NEW_LINE parent [ u ] = par NEW_LINE for child in adj [ u ] : NEW_LINE INDENT if ( child != par ) : NEW_LINE INDENT dfs ( child , u ) NEW_LINE DEDENT DEDENT DEDENT def countSmallerAncestors ( n ) : NEW_LINE INDENT global parent , adj NEW_LINE dfs ( 1 ) NEW_LINE for i in range ( 1 , n + 1 ) : NEW_LINE INDENT node = i NEW_LINE cnt = 0 NEW_LINE while ( parent [ node ] != - 1 ) : NEW_LINE INDENT if ( parent [ node ] < i ) : NEW_LINE INDENT cnt += 1 NEW_LINE DEDENT node = parent [ node ] NEW_LINE DEDENT print ( cnt , end = " ▁ " ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 6 NEW_LINE adj = [ [ ] for i in range ( 10 ** 5 ) ] NEW_LINE parent = [ 0 ] * ( 10 ** 5 ) NEW_LINE add_edge ( 1 , 5 ) NEW_LINE add_edge ( 1 , 4 ) NEW_LINE add_edge ( 4 , 6 ) NEW_LINE add_edge ( 5 , 3 ) NEW_LINE add_edge ( 5 , 2 ) NEW_LINE countSmallerAncestors ( N ) NEW_LINE DEDENT
Count subsequences having odd Bitwise XOR values from an array | Function to count the subsequences having odd bitwise XOR value ; Stores count of odd elements ; Stores count of even elements ; Traverse the array A [ ] ; If el is odd ; If count of odd elements is 0 ; Driver Code ; Given array A [ ] ; Function call to count subsequences having odd bitwise XOR value
def countSubsequences ( A ) : NEW_LINE INDENT odd = 0 NEW_LINE even = 0 NEW_LINE for el in A : NEW_LINE INDENT if ( el % 2 == 1 ) : NEW_LINE INDENT odd += 1 NEW_LINE DEDENT else : NEW_LINE INDENT even += 1 NEW_LINE DEDENT DEDENT if ( odd == 0 ) : NEW_LINE INDENT print ( 0 ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( 1 << len ( A ) - 1 ) NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT A = [ 1 , 3 , 4 ] NEW_LINE countSubsequences ( A ) NEW_LINE DEDENT
Maximum subarray product modulo M | Function to find maximum subarray product modulo M and minimum length of the subarray ; Stores maximum subarray product modulo M and minimum length of the subarray ; Stores the minimum length of subarray having maximum product ; Traverse the array ; Stores the product of a subarray ; Calculate Subarray whose start index is i ; Multiply product by arr [ i ] ; If product greater than ans ; Update ans ; Update length ; Print maximum subarray product mod M ; Print minimum length of subarray having maximum product ; Drivers Code
def maxModProdSubarr ( arr , n , M ) : NEW_LINE INDENT ans = 0 NEW_LINE length = n NEW_LINE for i in range ( n ) : NEW_LINE INDENT product = 1 NEW_LINE for j in range ( i , n , 1 ) : NEW_LINE INDENT product = ( product * arr [ i ] ) % M NEW_LINE if ( product > ans ) : NEW_LINE INDENT ans = product NEW_LINE if ( length > j - i + 1 ) : NEW_LINE INDENT length = j - i + 1 NEW_LINE DEDENT DEDENT DEDENT DEDENT print ( " Maximum ▁ subarray ▁ product ▁ is " , ans ) NEW_LINE print ( " Minimum ▁ length ▁ of ▁ the ▁ maximum ▁ product ▁ subarray ▁ is " , length ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 2 , 3 , 4 , 2 ] NEW_LINE N = len ( arr ) NEW_LINE M = 5 NEW_LINE maxModProdSubarr ( arr , N , M ) NEW_LINE DEDENT
Number of co | Python3 program for the above approach ; Function to check whether given integers are co - prime or not ; Utility function to count number of co - prime pairs ; Traverse the array ; If co - prime ; Increment count ; Return count ; Function to count number of co - prime pairs ; Stores digits in string form ; Sort the list ; Keep two copies of list l ; Generate 2 digit numbers using d1 and d2 ; If current number does not exceed N ; Stores length of list ; Stores number of co - prime pairs ; Print number of co - prime pairs ; Driver Code ; Given value of N , d1 , d2 ; Function call to count number of co - prime pairs
from copy import deepcopy NEW_LINE import math NEW_LINE def coprime ( a , b ) : NEW_LINE INDENT return ( math . gcd ( a , b ) ) == 1 NEW_LINE DEDENT def numOfPairs ( arr , N ) : NEW_LINE INDENT count = 0 NEW_LINE for i in range ( 0 , N - 1 ) : NEW_LINE INDENT for j in range ( i + 1 , N ) : NEW_LINE INDENT if ( coprime ( int ( arr [ i ] ) , int ( arr [ j ] ) ) ) : NEW_LINE INDENT count = count + 1 NEW_LINE DEDENT DEDENT DEDENT return count NEW_LINE DEDENT def noOfCoPrimePairs ( N , d1 , d2 ) : NEW_LINE INDENT l = [ ] NEW_LINE l . append ( str ( d1 ) ) NEW_LINE l . append ( str ( d2 ) ) NEW_LINE l . sort ( ) NEW_LINE if int ( N ) < int ( l [ 1 ] ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT total = temp2 = deepcopy ( l ) NEW_LINE flag = 0 NEW_LINE temp3 = [ ] NEW_LINE while len ( l [ 0 ] ) < 10 : NEW_LINE INDENT for i in range ( len ( l ) ) : NEW_LINE INDENT for j in range ( 2 ) : NEW_LINE INDENT if int ( l [ i ] + temp2 [ j ] ) > int ( N ) : NEW_LINE INDENT flag = 1 NEW_LINE break NEW_LINE DEDENT total . append ( l [ i ] + temp2 [ j ] ) NEW_LINE temp3 . append ( l [ i ] + temp2 [ j ] ) NEW_LINE DEDENT if flag == 1 : NEW_LINE INDENT break NEW_LINE DEDENT DEDENT if flag == 1 : NEW_LINE INDENT break NEW_LINE DEDENT l = deepcopy ( temp3 ) NEW_LINE temp3 = [ ] NEW_LINE DEDENT lenOfTotal = len ( total ) NEW_LINE ans = numOfPairs ( total , lenOfTotal ) NEW_LINE print ( ans ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT N = 30 NEW_LINE d1 = 2 NEW_LINE d2 = 3 NEW_LINE noOfCoPrimePairs ( N , d1 , d2 ) NEW_LINE DEDENT
Minimize cost of placing tiles of dimensions 2 * 1 over a Matrix | Function to find the minimum cost in placing N tiles in a grid M [ ] [ ] ; Stores the minimum profit after placing i tiles ; Traverse the grid [ ] [ ] ; Update the orig_cost ; Traverse over the range [ 2 , N ] ; Place tiles horizentally or vertically ; Print the answer ; Driver Code
def tile_placing ( grid , N ) : NEW_LINE INDENT dp = [ 0 ] * ( N + 5 ) ; NEW_LINE orig_cost = 0 ; NEW_LINE for i in range ( 2 ) : NEW_LINE INDENT for j in range ( N ) : NEW_LINE INDENT orig_cost += grid [ i ] [ j ] ; NEW_LINE DEDENT DEDENT dp [ 0 ] = 0 ; NEW_LINE dp [ 1 ] = abs ( grid [ 0 ] [ 0 ] - grid [ 1 ] [ 0 ] ) ; NEW_LINE for i in range ( 2 , N + 1 ) : NEW_LINE INDENT dp [ i ] = max ( dp [ i - 1 ] + abs ( grid [ 0 ] [ i - 1 ] - grid [ 1 ] [ i - 1 ] ) , dp [ i - 2 ] + abs ( grid [ 0 ] [ i - 2 ] - grid [ 0 ] [ i - 1 ] ) + abs ( grid [ 1 ] [ i - 2 ] - grid [ 1 ] [ i - 1 ] ) ) ; NEW_LINE DEDENT print ( orig_cost - dp [ N ] , end = " " ) ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT M = [ [ 7 , 5 , 1 , 3 ] , [ 8 , 6 , 0 , 2 ] ] ; NEW_LINE N = len ( M [ 0 ] ) ; NEW_LINE tile_placing ( M , N ) ; NEW_LINE DEDENT
Print indices of pair of array elements required to be removed to split array into 3 equal sum subarrays | Function to check if array can be split into three equal sum subarrays by removing two elements ; Stores sum of all three subarrays ; Sum of left subarray ; Sum of middle subarray ; Sum of right subarray ; Check if sum of subarrays are equal ; Print the possible pair ; If no pair exists , print - 1 ; Driver code ; Given array ; Size of the array
def findSplit ( arr , N ) : NEW_LINE INDENT for l in range ( 1 , N - 3 , 1 ) : NEW_LINE INDENT for r in range ( l + 2 , N - 1 , 1 ) : NEW_LINE INDENT lsum = 0 NEW_LINE rsum = 0 NEW_LINE msum = 0 NEW_LINE for i in range ( 0 , l , 1 ) : NEW_LINE INDENT lsum += arr [ i ] NEW_LINE DEDENT for i in range ( l + 1 , r , 1 ) : NEW_LINE INDENT msum += arr [ i ] NEW_LINE DEDENT for i in range ( r + 1 , N , 1 ) : NEW_LINE INDENT rsum += arr [ i ] NEW_LINE DEDENT if ( lsum == rsum and rsum == msum ) : NEW_LINE INDENT print ( l , r ) NEW_LINE return NEW_LINE DEDENT DEDENT DEDENT print ( - 1 ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 2 , 5 , 12 , 7 , 19 , 4 , 3 ] NEW_LINE N = len ( arr ) NEW_LINE findSplit ( arr , N ) NEW_LINE DEDENT
Count the number of times a Bulb switches its state | Python program for the above approach ; Function to find the number of times a bulb switches its state ; count of 1 's ; Traverse the array ; update the array ; update the status of bulb ; Traverse the array Q [ ] ; stores previous state of the bulb ; Toggle the switch and update the count of 1 's ; if the bulb switches state ; Return count ; Input ; Queries ; Function call to find number of times the bulb toggles
import math NEW_LINE def solve ( A , n , Q , q ) : NEW_LINE INDENT one = 0 NEW_LINE for i in range ( 0 , n ) : NEW_LINE INDENT if ( A [ i ] == 1 ) : NEW_LINE INDENT one += 1 NEW_LINE DEDENT DEDENT glows = 0 NEW_LINE count = 0 NEW_LINE if ( one >= int ( math . ceil ( n / 2 ) ) ) : NEW_LINE INDENT glows = 1 NEW_LINE DEDENT for i in range ( 0 , q ) : NEW_LINE INDENT prev = glows NEW_LINE if ( A [ Q [ i ] - 1 ] == 1 ) : NEW_LINE INDENT one -= 1 NEW_LINE DEDENT if ( A [ Q [ i ] - 1 ] == 0 ) : NEW_LINE INDENT one += 1 NEW_LINE DEDENT A [ Q [ i ] - 1 ] ^= 1 NEW_LINE if ( one >= int ( math . ceil ( n / 2.0 ) ) ) : NEW_LINE INDENT glows = 1 NEW_LINE DEDENT else : NEW_LINE INDENT glows = 0 NEW_LINE DEDENT if ( prev != glows ) : NEW_LINE INDENT count += 1 NEW_LINE DEDENT DEDENT return count NEW_LINE DEDENT n = 3 NEW_LINE arr = [ 1 , 1 , 0 ] NEW_LINE q = 3 NEW_LINE Q = [ 3 , 2 , 1 ] NEW_LINE print ( solve ( arr , n , Q , q ) ) NEW_LINE
Count array elements having sum of digits equal to K | Function to calculate the sum of digits of the number N ; Stores the sum of digits ; Return the sum ; Function to count array elements ; Store the count of array elements having sum of digits K ; Traverse the array ; If sum of digits is equal to K ; Increment the count ; Prthe count ; Given array ; Given value of K ; Size of the array ; Function call to count array elements having sum of digits equal to K
def sumOfDigits ( N ) : NEW_LINE INDENT sum = 0 NEW_LINE while ( N != 0 ) : NEW_LINE INDENT sum += N % 10 NEW_LINE N //= 10 NEW_LINE DEDENT return sum NEW_LINE DEDENT def elementsHavingDigitSumK ( arr , N , K ) : NEW_LINE INDENT count = 0 NEW_LINE for i in range ( N ) : NEW_LINE INDENT if ( sumOfDigits ( arr [ i ] ) == K ) : NEW_LINE INDENT count += 1 NEW_LINE DEDENT DEDENT print ( count ) NEW_LINE DEDENT arr = [ 23 , 54 , 87 , 29 , 92 , 62 ] NEW_LINE K = 11 NEW_LINE N = len ( arr ) NEW_LINE elementsHavingDigitSumK ( arr , N , K ) NEW_LINE
Postfix to Infix | Python3 program to find infix for a given postfix . ; Get Infix for a given postfix expression ; Push operands ; We assume that input is a valid postfix and expect an operator . ; There must be a single element in stack now which is the required infix . ; Driver Code
def isOperand ( x ) : NEW_LINE INDENT return ( ( x >= ' a ' and x <= ' z ' ) or ( x >= ' A ' and x <= ' Z ' ) ) NEW_LINE DEDENT def getInfix ( exp ) : NEW_LINE INDENT s = [ ] NEW_LINE for i in exp : NEW_LINE INDENT if ( isOperand ( i ) ) : NEW_LINE INDENT s . insert ( 0 , i ) NEW_LINE DEDENT else : NEW_LINE INDENT op1 = s [ 0 ] NEW_LINE s . pop ( 0 ) NEW_LINE op2 = s [ 0 ] NEW_LINE s . pop ( 0 ) NEW_LINE s . insert ( 0 , " ( " + op2 + i + op1 + " ) " ) NEW_LINE DEDENT DEDENT return s [ 0 ] NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT exp = " ab * c + " NEW_LINE print ( getInfix ( exp . strip ( ) ) ) NEW_LINE DEDENT
Change a Binary Tree so that every node stores sum of all nodes in left subtree | Python3 program to store sum of nodes in left subtree in every node Binary Tree Node utility that allocates a new Node with the given key ; Construct to create a new node ; Function to modify a Binary Tree so that every node stores sum of values in its left child including its own value ; Base cases ; Update left and right subtrees ; Add leftsum to current node ; Return sum of values under root ; Utility function to do inorder traversal ; Driver Code ; Let us con below tree 1 / \ 2 3 / \ \ 4 5 6
class newNode : NEW_LINE INDENT def __init__ ( self , key ) : NEW_LINE INDENT self . data = key NEW_LINE self . left = None NEW_LINE self . right = None NEW_LINE DEDENT DEDENT def updatetree ( root ) : NEW_LINE INDENT if ( not root ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT if ( root . left == None and root . right == None ) : NEW_LINE INDENT return root . data NEW_LINE DEDENT leftsum = updatetree ( root . left ) NEW_LINE rightsum = updatetree ( root . right ) NEW_LINE root . data += leftsum NEW_LINE return root . data + rightsum NEW_LINE DEDENT def inorder ( node ) : NEW_LINE INDENT if ( node == None ) : NEW_LINE INDENT return NEW_LINE DEDENT inorder ( node . left ) NEW_LINE print ( node . data , end = " ▁ " ) NEW_LINE inorder ( node . right ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT root = newNode ( 1 ) NEW_LINE root . left = newNode ( 2 ) NEW_LINE root . right = newNode ( 3 ) NEW_LINE root . left . left = newNode ( 4 ) NEW_LINE root . left . right = newNode ( 5 ) NEW_LINE root . right . right = newNode ( 6 ) NEW_LINE updatetree ( root ) NEW_LINE print ( " Inorder ▁ traversal ▁ of ▁ the ▁ modified ▁ tree ▁ is " ) NEW_LINE inorder ( root ) NEW_LINE DEDENT
The Stock Span Problem | Fills list S [ ] with span values ; Span value of first day is always 1 ; Calculate span value of remaining days by linearly checking previous days ; Initialize span value ; Traverse left while the next element on left is smaller than price [ i ] ; A utility function to print elements of array ; Driver program to test above function ; Fill the span values in list S [ ] ; print the calculated span values
def calculateSpan ( price , n , S ) : NEW_LINE INDENT S [ 0 ] = 1 NEW_LINE for i in range ( 1 , n , 1 ) : NEW_LINE INDENT S [ i ] = 1 NEW_LINE j = i - 1 NEW_LINE while ( j >= 0 ) and ( price [ i ] >= price [ j ] ) : NEW_LINE INDENT S [ i ] += 1 NEW_LINE j -= 1 NEW_LINE DEDENT DEDENT DEDENT def printArray ( arr , n ) : NEW_LINE INDENT for i in range ( n ) : NEW_LINE INDENT print ( arr [ i ] , end = " ▁ " ) NEW_LINE DEDENT DEDENT price = [ 10 , 4 , 5 , 90 , 120 , 80 ] NEW_LINE n = len ( price ) NEW_LINE S = [ None ] * n NEW_LINE calculateSpan ( price , n , S ) NEW_LINE printArray ( S , n ) NEW_LINE
The Stock Span Problem | A stack based efficient method to calculate s ; Create a stack and push index of fist element to it ; Span value of first element is always 1 ; Calculate span values for rest of the elements ; Pop elements from stack whlie stack is not empty and top of stack is smaller than price [ i ] ; If stack becomes empty , then price [ i ] is greater than all elements on left of it , i . e . price [ 0 ] , price [ 1 ] , . . price [ i - 1 ] . Else the price [ i ] is greater than elements after top of stack ; Push this element to stack ; A utility function to print elements of array ; Driver program to test above function ; Fill the span values in array S [ ] ; Print the calculated span values
def calculateSpan ( price , S ) : NEW_LINE INDENT n = len ( price ) NEW_LINE st = [ ] NEW_LINE st . append ( 0 ) NEW_LINE S [ 0 ] = 1 NEW_LINE for i in range ( 1 , n ) : NEW_LINE INDENT while ( len ( st ) > 0 and price [ st [ - 1 ] ] <= price [ i ] ) : NEW_LINE INDENT st . pop ( ) NEW_LINE DEDENT S [ i ] = i + 1 if len ( st ) <= 0 else ( i - st [ - 1 ] ) NEW_LINE st . append ( i ) NEW_LINE DEDENT DEDENT def printArray ( arr , n ) : NEW_LINE INDENT for i in range ( 0 , n ) : NEW_LINE INDENT print ( arr [ i ] , end = " ▁ " ) NEW_LINE DEDENT DEDENT price = [ 10 , 4 , 5 , 90 , 120 , 80 ] NEW_LINE S = [ 0 for i in range ( len ( price ) + 1 ) ] NEW_LINE calculateSpan ( price , S ) NEW_LINE printArray ( S , len ( price ) ) NEW_LINE
The Stock Span Problem | An efficient method to calculate stock span values implementing the same idea without using stack ; Span value of first element is always 1 ; Calculate span values for rest of the elements ; A utility function to print elements of array ; Driver code ; Fill the span values in array S [ ] ; Print the calculated span values
def calculateSpan ( A , n , ans ) : NEW_LINE INDENT ans [ 0 ] = 1 NEW_LINE for i in range ( 1 , n ) : NEW_LINE INDENT counter = 1 NEW_LINE while ( ( i - counter ) >= 0 and A [ i ] >= A [ i - counter ] ) : NEW_LINE INDENT counter += ans [ i - counter ] NEW_LINE DEDENT ans [ i ] = counter NEW_LINE DEDENT DEDENT def printArray ( arr , n ) : NEW_LINE INDENT for i in range ( n ) : NEW_LINE INDENT print ( arr [ i ] , end = ' ▁ ' ) NEW_LINE DEDENT print ( ) NEW_LINE DEDENT price = [ 10 , 4 , 5 , 90 , 120 , 80 ] NEW_LINE n = len ( price ) NEW_LINE S = [ 0 ] * ( n ) NEW_LINE calculateSpan ( price , n , S ) NEW_LINE printArray ( S , n ) NEW_LINE
Next Greater Element | Function to print element and NGE pair for all elements of list ; Driver program to test above function
def printNGE ( arr ) : NEW_LINE INDENT for i in range ( 0 , len ( arr ) , 1 ) : NEW_LINE INDENT next = - 1 NEW_LINE for j in range ( i + 1 , len ( arr ) , 1 ) : NEW_LINE INDENT if arr [ i ] < arr [ j ] : NEW_LINE INDENT next = arr [ j ] NEW_LINE break NEW_LINE DEDENT DEDENT print ( str ( arr [ i ] ) + " ▁ - - ▁ " + str ( next ) ) NEW_LINE DEDENT DEDENT arr = [ 11 , 13 , 21 , 3 ] NEW_LINE printNGE ( arr ) NEW_LINE
Convert a Binary Tree into its Mirror Tree | Utility function to create a new tree node ; Change a tree so that the roles of the left and right pointers are swapped at every node . So the tree ... 4 / \ 2 5 / \ 1 3 is changed to ... 4 / \ 5 2 / \ 3 1 ; do the subtrees ; swap the pointers in this node ; Helper function to print Inorder traversal . ; Driver code ; Print inorder traversal of the input tree ; Convert tree to its mirror ; Print inorder traversal of the mirror tree
class newNode : NEW_LINE INDENT def __init__ ( self , data ) : NEW_LINE INDENT self . data = data NEW_LINE self . left = self . right = None NEW_LINE DEDENT DEDENT def mirror ( node ) : NEW_LINE INDENT if ( node == None ) : NEW_LINE INDENT return NEW_LINE DEDENT else : NEW_LINE INDENT temp = node NEW_LINE mirror ( node . left ) NEW_LINE mirror ( node . right ) NEW_LINE temp = node . left NEW_LINE node . left = node . right NEW_LINE node . right = temp NEW_LINE DEDENT DEDENT def inOrder ( node ) : NEW_LINE INDENT if ( node == None ) : NEW_LINE INDENT return NEW_LINE DEDENT inOrder ( node . left ) NEW_LINE print ( node . data , end = " ▁ " ) NEW_LINE inOrder ( node . right ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT root = newNode ( 1 ) NEW_LINE root . left = newNode ( 2 ) NEW_LINE root . right = newNode ( 3 ) NEW_LINE root . left . left = newNode ( 4 ) NEW_LINE root . left . right = newNode ( 5 ) NEW_LINE print ( " Inorder ▁ traversal ▁ of ▁ the " , " constructed ▁ tree ▁ is " ) NEW_LINE inOrder ( root ) NEW_LINE mirror ( root ) NEW_LINE print ( " Inorder traversal of " , ▁ " the mirror treeis " ) NEW_LINE inOrder ( root ) NEW_LINE DEDENT
Maximum product of indexes of next greater on left and right | Method to find the next greater value in left side ; Checking if current element is greater than top ; Pop the element till we can 't get the larger value then the current value ; Else push the element in the stack ; Method to find the next greater value in right ; Checking if current element is greater than top ; Pop the element till we can 't get the larger value then the current value ; Else push the element in the stack ; For each element storing the index of just greater element in left side ; For each element storing the index of just greater element in right side ; Finding the max index product ; Driver Code
def nextGreaterInLeft ( a ) : NEW_LINE INDENT left_index = [ 0 ] * len ( a ) NEW_LINE s = [ ] NEW_LINE for i in range ( len ( a ) ) : NEW_LINE INDENT while len ( s ) != 0 and a [ i ] >= a [ s [ - 1 ] ] : NEW_LINE INDENT s . pop ( ) NEW_LINE DEDENT if len ( s ) != 0 : NEW_LINE INDENT left_index [ i ] = s [ - 1 ] NEW_LINE DEDENT else : NEW_LINE INDENT left_index [ i ] = 0 NEW_LINE DEDENT s . append ( i ) NEW_LINE DEDENT return left_index NEW_LINE DEDENT def nextGreaterInRight ( a ) : NEW_LINE INDENT right_index = [ 0 ] * len ( a ) NEW_LINE s = [ ] NEW_LINE for i in range ( len ( a ) - 1 , - 1 , - 1 ) : NEW_LINE INDENT while len ( s ) != 0 and a [ i ] >= a [ s [ - 1 ] ] : NEW_LINE INDENT s . pop ( ) NEW_LINE DEDENT if len ( s ) != 0 : NEW_LINE INDENT right_index [ i ] = s [ - 1 ] NEW_LINE DEDENT else : NEW_LINE INDENT right_index [ i ] = 0 NEW_LINE DEDENT s . append ( i ) NEW_LINE DEDENT return right_index NEW_LINE DEDENT def LRProduct ( arr ) : NEW_LINE INDENT left = nextGreaterInLeft ( arr ) NEW_LINE right = nextGreaterInRight ( arr ) NEW_LINE ans = - 1 NEW_LINE for i in range ( 1 , len ( left ) - 1 ) : NEW_LINE INDENT if left [ i ] == 0 or right [ i ] == 0 : NEW_LINE INDENT ans = max ( ans , 0 ) NEW_LINE DEDENT else : NEW_LINE INDENT temp = ( left [ i ] + 1 ) * ( right [ i ] + 1 ) NEW_LINE ans = max ( ans , temp ) NEW_LINE DEDENT DEDENT return ans NEW_LINE DEDENT arr = [ 5 , 4 , 3 , 4 , 5 ] NEW_LINE print ( LRProduct ( arr ) ) NEW_LINE
The Celebrity Problem | Max ; Person with 2 is celebrity ; Returns - 1 if celebrity is not present . If present , returns id ( value from 0 to n - 1 ) ; The graph needs not be constructed as the edges can be found by using knows function degree array ; ; Query for all edges ; Set the degrees ; Find a person with indegree n - 1 and out degree 0 ; Driver code
N = 8 NEW_LINE MATRIX = [ [ 0 , 0 , 1 , 0 ] , [ 0 , 0 , 1 , 0 ] , [ 0 , 0 , 0 , 0 ] , [ 0 , 0 , 1 , 0 ] ] NEW_LINE def knows ( a , b ) : NEW_LINE INDENT return MATRIX [ a ] [ b ] NEW_LINE DEDENT def findCelebrity ( n ) : NEW_LINE INDENT indegree = [ 0 for x in range ( n ) ] NEW_LINE outdegree = [ 0 for x in range ( n ) ] NEW_LINE for i in range ( n ) : NEW_LINE INDENT for j in range ( n ) : NEW_LINE INDENT x = knows ( i , j ) NEW_LINE outdegree [ i ] += x NEW_LINE indegree [ j ] += x NEW_LINE DEDENT DEDENT for i in range ( n ) : NEW_LINE INDENT if ( indegree [ i ] == n - 1 and outdegree [ i ] == 0 ) : NEW_LINE INDENT return i NEW_LINE DEDENT DEDENT return - 1 NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT n = 4 NEW_LINE id_ = findCelebrity ( n ) NEW_LINE if id_ == - 1 : NEW_LINE INDENT print ( " No ▁ celebrity " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " Celebrity ▁ ID " , id_ ) NEW_LINE DEDENT DEDENT
The Celebrity Problem | Max ; Person with 2 is celebrity ; Returns - 1 if a potential celebrity is not present . If present , returns id ( value from 0 to n - 1 ) . ; Base case ; Find the celebrity with n - 1 persons ; If there are no celebrities ; if the id knows the nth person then the id cannot be a celebrity , but nth person could be on ; if the id knows the nth person then the id cannot be a celebrity , but nth person could be one ; If there is no celebrity ; Returns - 1 if celebrity is not present . If present , returns id ( value from 0 to n - 1 ) . a wrapper over findCelebrity ; Find the celebrity ; Check if the celebrity found is really the celebrity ; Check the id is really the celebrity ; If the person is known to everyone . ; Driver code
N = 8 NEW_LINE MATRIX = [ [ 0 , 0 , 1 , 0 ] , [ 0 , 0 , 1 , 0 ] , [ 0 , 0 , 0 , 0 ] , [ 0 , 0 , 1 , 0 ] ] NEW_LINE def knows ( a , b ) : NEW_LINE INDENT return MATRIX [ a ] [ b ] NEW_LINE DEDENT def findPotentialCelebrity ( n ) : NEW_LINE INDENT if ( n == 0 ) : NEW_LINE INDENT return 0 ; NEW_LINE DEDENT id_ = findPotentialCelebrity ( n - 1 ) NEW_LINE if ( id_ == - 1 ) : NEW_LINE INDENT return n - 1 NEW_LINE DEDENT elif knows ( id_ , n - 1 ) : NEW_LINE INDENT return n - 1 NEW_LINE DEDENT elif knows ( n - 1 , id_ ) : NEW_LINE INDENT return id_ NEW_LINE DEDENT return - 1 NEW_LINE DEDENT def Celebrity ( n ) : NEW_LINE INDENT id_ = findPotentialCelebrity ( n ) NEW_LINE if ( id_ == - 1 ) : NEW_LINE INDENT return id_ NEW_LINE DEDENT else : NEW_LINE INDENT c1 = 0 NEW_LINE c2 = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( i != id_ ) : NEW_LINE INDENT c1 += knows ( id_ , i ) NEW_LINE c2 += knows ( i , id_ ) NEW_LINE DEDENT DEDENT if ( c1 == 0 and c2 == n - 1 ) : NEW_LINE INDENT return id_ NEW_LINE DEDENT return - 1 NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT n = 4 NEW_LINE id_ = Celebrity ( n ) NEW_LINE if id_ == - 1 : NEW_LINE INDENT print ( " No ▁ celebrity " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " Celebrity ▁ ID " , id_ ) NEW_LINE DEDENT DEDENT
Convert a Binary Tree into its Mirror Tree | A binary tree node has data , pointer to left child and a pointer to right child Helper function that allocates a new node with the given data and None left and right pointers ; Change a tree so that the roles of the left and right pointers are swapped at every node . So the tree ... 4 / \ 2 5 / \ 1 3 is changed to ... 4 / \ 5 2 / \ 3 1 ; Do BFS . While doing BFS , keep swapping left and right children ; pop top node from queue ; swap left child with right child ; append left and right children ; Helper function to print Inorder traversal . ; Driver code ; Print inorder traversal of the input tree ; Convert tree to its mirror ; Print inorder traversal of the mirror tree
class newNode : 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 mirror ( root ) : NEW_LINE INDENT if ( root == None ) : NEW_LINE INDENT return NEW_LINE DEDENT q = [ ] NEW_LINE q . append ( root ) NEW_LINE while ( len ( q ) ) : NEW_LINE INDENT curr = q [ 0 ] NEW_LINE q . pop ( 0 ) NEW_LINE curr . left , curr . right = curr . right , curr . left NEW_LINE if ( curr . left ) : NEW_LINE INDENT q . append ( curr . left ) NEW_LINE DEDENT if ( curr . right ) : NEW_LINE INDENT q . append ( curr . right ) NEW_LINE DEDENT DEDENT DEDENT def inOrder ( node ) : NEW_LINE INDENT if ( node == None ) : NEW_LINE INDENT return NEW_LINE DEDENT inOrder ( node . left ) NEW_LINE print ( node . data , end = " ▁ " ) NEW_LINE inOrder ( node . right ) NEW_LINE DEDENT root = newNode ( 1 ) NEW_LINE root . left = newNode ( 2 ) NEW_LINE root . right = newNode ( 3 ) NEW_LINE root . left . left = newNode ( 4 ) NEW_LINE root . left . right = newNode ( 5 ) NEW_LINE print ( " Inorder ▁ traversal ▁ of ▁ the ▁ constructed ▁ tree ▁ is " ) NEW_LINE inOrder ( root ) NEW_LINE mirror ( root ) NEW_LINE print ( " Inorder traversal of the mirror tree is " ) NEW_LINE inOrder ( root ) NEW_LINE
Delete middle element of a stack | Deletes middle of stack of size n . Curr is current item number ; If stack is empty or all items are traversed ; Remove current item ; Remove other items ; Put all items back except middle ; Driver function to test above functions ; push elements into the stack ; Printing stack after deletion of middle .
class Stack : NEW_LINE INDENT def __init__ ( self ) : NEW_LINE INDENT self . items = [ ] NEW_LINE DEDENT def isEmpty ( self ) : NEW_LINE INDENT return self . items == [ ] NEW_LINE DEDENT def push ( self , item ) : NEW_LINE INDENT self . items . append ( item ) NEW_LINE DEDENT def pop ( self ) : NEW_LINE INDENT return self . items . pop ( ) NEW_LINE DEDENT def peek ( self ) : NEW_LINE INDENT return self . items [ len ( self . items ) - 1 ] NEW_LINE DEDENT def size ( self ) : NEW_LINE INDENT return len ( self . items ) NEW_LINE DEDENT DEDENT def deleteMid ( st , n , curr ) : NEW_LINE INDENT if ( st . isEmpty ( ) or curr == n ) : NEW_LINE INDENT return NEW_LINE DEDENT x = st . peek ( ) NEW_LINE st . pop ( ) NEW_LINE deleteMid ( st , n , curr + 1 ) NEW_LINE if ( curr != int ( n / 2 ) ) : NEW_LINE INDENT st . push ( x ) NEW_LINE DEDENT DEDENT st = Stack ( ) NEW_LINE st . push ( '1' ) NEW_LINE st . push ( '2' ) NEW_LINE st . push ( '3' ) NEW_LINE st . push ( '4' ) NEW_LINE st . push ( '5' ) NEW_LINE st . push ( '6' ) NEW_LINE st . push ( '7' ) NEW_LINE deleteMid ( st , st . size ( ) , 0 ) NEW_LINE while ( st . isEmpty ( ) == False ) : NEW_LINE INDENT p = st . peek ( ) NEW_LINE st . pop ( ) NEW_LINE print ( str ( p ) + " ▁ " , end = " " ) NEW_LINE DEDENT
Sorting array using Stacks | This function return the sorted stack ; pop out the first element ; while temporary stack is not empty and top of stack is smaller than temp ; pop from temporary stack and append it to the input stack ; append temp in tempory of stack ; append array elements to stack ; Sort the temporary stack ; Put stack elements in arrp [ ] ; Driver code
def sortStack ( input ) : NEW_LINE INDENT tmpStack = [ ] NEW_LINE while ( len ( input ) > 0 ) : NEW_LINE INDENT tmp = input [ - 1 ] NEW_LINE input . pop ( ) NEW_LINE while ( len ( tmpStack ) > 0 and tmpStack [ - 1 ] < tmp ) : NEW_LINE INDENT input . append ( tmpStack [ - 1 ] ) NEW_LINE tmpStack . pop ( ) NEW_LINE DEDENT tmpStack . append ( tmp ) NEW_LINE DEDENT return tmpStack NEW_LINE DEDENT def sortArrayUsingStacks ( arr , n ) : NEW_LINE INDENT input = [ ] NEW_LINE i = 0 NEW_LINE while ( i < n ) : NEW_LINE INDENT input . append ( arr [ i ] ) NEW_LINE i = i + 1 NEW_LINE DEDENT tmpStack = sortStack ( input ) NEW_LINE i = 0 NEW_LINE while ( i < n ) : NEW_LINE INDENT arr [ i ] = tmpStack [ - 1 ] NEW_LINE tmpStack . pop ( ) NEW_LINE i = i + 1 NEW_LINE DEDENT return arr NEW_LINE DEDENT arr = [ 10 , 5 , 15 , 45 ] NEW_LINE n = len ( arr ) NEW_LINE arr = sortArrayUsingStacks ( arr , n ) NEW_LINE i = 0 NEW_LINE while ( i < n ) : NEW_LINE INDENT print ( arr [ i ] , end = " ▁ " ) NEW_LINE i = i + 1 NEW_LINE DEDENT