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_L...
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 ; radiu...
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 INDE...
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 ; D...
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 s...
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 a...
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...
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_L...
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 ▁ ...
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 ...
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 ( diagonalLen...
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 c...
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 s...
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_pentade...
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 ▁ cente...
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 ▁ : ▁ " , hendecag...
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 ▁ numb...
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 ) f...
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 ) :...
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...
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 ( " ye...
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_...
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 dimension...
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 pri...
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 ...
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 ...
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...
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 c...
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...
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 D...
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...
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 ( " Pol...
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 ...
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 ) ...
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 t...
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 )...
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 j...
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...
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 ;...
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 ...
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 ...
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 i...
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...
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 ,...
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 i...
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 cod...
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 ( sm...
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 con...
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 ...
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 t...
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 - ...
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 gc...
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...
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...
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 I...
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 ...
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_LI...
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...
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...
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...
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_L...
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 [...
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...
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 distinc...
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 ...
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 ) ; Func...
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 NE...
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 ...
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 ; P...
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__ =...
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 ...
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 ...
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 ; Ma...
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 ] == Fals...
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 arra...
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 ...
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_...
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 /...
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 ] = F...
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 ...
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 __...
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...
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 ( len...
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 INDEN...
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 ; ...
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 r...
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 cu...
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 ...
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 [ ] ; Travers...
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_L...
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 ...
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 s...
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 ) ...
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...
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 replacebyNearestPowe...
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 d...
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...
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...
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 (...
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 o...
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 NE...
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 er...
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...
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 ar...
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...
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...
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 ) )...
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 t...
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...
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 t...
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 pri...
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 ; Functi...
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 ...
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 c...
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 ...
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 ;...
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 ...
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 for...
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 ...
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 ; ...
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 ] ) ;...
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 i...
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 ) : ...
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 swi...
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 DEDE...
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 c...
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 ] ) ==...
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 ...
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...
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 =...
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 ...
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 ) : ...
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 sta...
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...
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 [ ] ; Prin...
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 print...
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...
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 ...
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...
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 ...
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_LIN...
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 indegr...
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 )...
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 ...
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_ = findPoten...
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...
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_LI...
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 ...
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 s...
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 st...
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 DEDEN...