text stringlengths 17 3.65k | code stringlengths 70 5.84k |
|---|---|
Find if a point lies inside , outside or on the circumcircle of three points A , B , C | Function to find the line given two points ; Function which converts the input line to its perpendicular bisector . It also inputs the points whose mid - lies o on the bisector ; Find the mid point ; x coordinates ; y coordinates ;... | def lineFromPoints ( P , Q , a , b , c ) : NEW_LINE INDENT a = Q [ 1 ] - P [ 1 ] NEW_LINE b = P [ 0 ] - Q [ 0 ] NEW_LINE c = a * ( P [ 0 ] ) + b * ( P [ 1 ] ) NEW_LINE return a , b , c NEW_LINE DEDENT def perpenBisectorFromLine ( P , Q , a , b , c ) : NEW_LINE INDENT mid_point = [ 0 , 0 ] NEW_LINE mid_point [ 0 ] = ( P... |
Find the maximum angle at which we can tilt the bottle without spilling any water | Python3 program to find the maximum angle at which we can tilt the bottle without spilling any water ; Now we have the volume of rectangular prism a * a * b ; Now we have 2 cases ! ; Taking the tangent inverse of value d As we want to t... | from math import * NEW_LINE def find_angle ( x , y , z ) : NEW_LINE INDENT volume = x * x * y ; NEW_LINE ans = 0 ; NEW_LINE if ( z < volume // 2 ) : NEW_LINE INDENT d = ( x * y * y ) / ( 2.0 * z ) ; NEW_LINE ans = atan ( d ) ; NEW_LINE DEDENT else : NEW_LINE INDENT z = volume - z ; NEW_LINE d = ( 2 * z ) / ( float ) ( ... |
Count of distinct rectangles inscribed in an equilateral triangle | Function to return the count of rectangles when n is odd ; Calculating number of dots in vertical level ; Calculating number of ways to select two points in the horizontal level i ; Multiply both to obtain the number of rectangles formed at that level ... | def countOdd ( n ) : NEW_LINE INDENT coun = 0 NEW_LINE i = n - 2 NEW_LINE while ( i >= 1 ) : NEW_LINE INDENT if ( i & 1 ) : NEW_LINE INDENT m = int ( ( n - i ) / 2 ) NEW_LINE j = int ( ( i * ( i + 1 ) ) / 2 ) NEW_LINE coun += j * m NEW_LINE DEDENT else : NEW_LINE INDENT m = int ( ( ( n - 1 ) - i ) / 2 ) NEW_LINE j = in... |
Find same contacts in a list of contacts | Structure for storing contact details . ; A utility function to fill entries in adjacency matrix representation of graph ; Initialize the adjacency matrix ; Traverse through all contacts ; Add mat from i to j and vice versa , if possible . Since length of each contact field is... | class contact : NEW_LINE INDENT def __init__ ( self , field1 , field2 , field3 ) : NEW_LINE INDENT self . field1 = field1 NEW_LINE self . field2 = field2 NEW_LINE self . field3 = field3 NEW_LINE DEDENT DEDENT def buildGraph ( arr , n , mat ) : NEW_LINE INDENT for i in range ( n ) : NEW_LINE INDENT for j in range ( n ) ... |
Area of the biggest ellipse inscribed within a rectangle | Function to find the area of the ellipse ; The sides cannot be negative ; Area of the ellipse ; Driver code | def ellipse ( l , b ) : NEW_LINE INDENT if l < 0 or b < 0 : NEW_LINE INDENT return - 1 NEW_LINE DEDENT x = ( 3.14 * l * b ) / 4 NEW_LINE return x NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT l , b = 5 , 3 NEW_LINE print ( ellipse ( l , b ) ) NEW_LINE DEDENT |
Determine the number of squares of unit area that a given line will pass through . | Python3 program to determine the number of squares that line will pass through ; Function to return the required position ; Driver Code | from math import gcd NEW_LINE def noOfSquares ( x1 , y1 , x2 , y2 ) : NEW_LINE INDENT dx = abs ( x2 - x1 ) ; NEW_LINE dy = abs ( y2 - y1 ) ; NEW_LINE ans = dx + dy - gcd ( dx , dy ) ; NEW_LINE print ( ans ) ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT x1 = 1 ; y1 = 1 ; x2 = 4 ; y2 = 3 ; NEW_LINE ... |
Count paths with distance equal to Manhattan distance | Function to return the value of nCk ; Since C ( n , k ) = C ( n , n - k ) ; Calculate value of [ n * ( n - 1 ) * -- - * ( n - k + 1 ) ] / [ k * ( k - 1 ) * -- - * 1 ] ; Function to return the number of paths ; Difference between the ' x ' coordinates of the given ... | def binomialCoeff ( n , k ) : NEW_LINE INDENT res = 1 NEW_LINE if ( k > n - k ) : NEW_LINE INDENT k = n - k NEW_LINE DEDENT for i in range ( k ) : NEW_LINE INDENT res *= ( n - i ) NEW_LINE res //= ( i + 1 ) NEW_LINE DEDENT return res NEW_LINE DEDENT def countPaths ( x1 , y1 , x2 , y2 ) : NEW_LINE INDENT m = abs ( x1 - ... |
Find the area of largest circle inscribed in ellipse | Python3 program implementation of above approach ; Area of the Reuleaux triangle ; Driver Code | import math NEW_LINE def areaCircle ( b ) : NEW_LINE INDENT area = math . pi * b * b NEW_LINE return area NEW_LINE DEDENT a = 10 NEW_LINE b = 8 NEW_LINE print ( areaCircle ( b ) ) NEW_LINE |
Section formula for 3 D | Function to find the section of the line ; Applying section formula ; Printing result ; Driver code | def section ( x1 , x2 , y1 , y2 , z1 , z2 , m , n ) : NEW_LINE INDENT x = ( ( m * x2 ) + ( n * x1 ) ) / ( m + n ) NEW_LINE y = ( ( m * y2 ) + ( n * y1 ) ) / ( m + n ) NEW_LINE z = ( ( m * z2 ) + ( n * z1 ) ) / ( m + n ) NEW_LINE print ( " ( " , x , " , " , y , " , " , z , " ) " ) NEW_LINE DEDENT if __name__ == ' _ _ ma... |
Program to find the Circumcircle of any regular polygon | Python3 Program to find the radius of the circumcircle of the given polygon ; Function to find the radius of the circumcircle ; these cannot be negative ; Radius of the circumcircle ; Return the radius ; Driver code ; Find the radius of the circumcircle | from math import * NEW_LINE def findRadiusOfcircumcircle ( n , a ) : NEW_LINE INDENT if n < 0 or a < 0 : NEW_LINE INDENT return - 1 NEW_LINE DEDENT radius = a / sqrt ( 2 - ( 2 * cos ( 360 / n ) ) ) NEW_LINE return radius NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT n , a = 5 , 6 NEW_LINE print ( ro... |
Program to find the Radius of the incircle of the triangle | Function to find the radius of the incircle ; the sides cannot be negative ; semi - perimeter of the circle ; area of the triangle ; Radius of the incircle ; Return the radius ; Driver code ; Get the sides of the triangle ; Find the radius of the incircle | def findRadiusOfIncircle ( a , b , c ) : NEW_LINE INDENT if ( a < 0 or b < 0 or c < 0 ) : NEW_LINE INDENT return - 1 NEW_LINE DEDENT p = ( a + b + c ) / 2 NEW_LINE area = sqrt ( p * ( p - a ) * ( p - b ) * ( p - c ) ) NEW_LINE radius = area / p NEW_LINE return radius NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NE... |
Find area of triangle if two vectors of two adjacent sides are given | Python code to calculate area of triangle if vectors of 2 adjacent sides are given ; function to calculate area of triangle ; driver code | import math NEW_LINE def area ( x1 , y1 , z1 , x2 , y2 , z2 ) : NEW_LINE INDENT area = math . sqrt ( ( y1 * z2 - y2 * z1 ) ** 2 + ( x1 * z2 - x2 * z1 ) ** 2 + ( x1 * y2 - x2 * y1 ) ** 2 ) NEW_LINE area = area / 2 NEW_LINE return area NEW_LINE DEDENT def main ( ) : NEW_LINE INDENT x1 = - 2 NEW_LINE y1 = 0 NEW_LINE z1 = ... |
Largest trapezoid that can be inscribed in a semicircle | Python 3 Program to find the biggest trapezoid which can be inscribed within the semicircle ; Function to find the area of the biggest trapezoid ; the radius cannot be negative ; area of the trapezoid ; Driver code | from math import * NEW_LINE def trapezoidarea ( r ) : NEW_LINE INDENT if r < 0 : NEW_LINE INDENT return - 1 NEW_LINE DEDENT a = ( 3 * sqrt ( 3 ) * pow ( r , 2 ) ) / 4 NEW_LINE return a NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT r = 5 NEW_LINE print ( round ( trapezoidarea ( r ) , 3 ) ) NEW_LINE D... |
Largest rectangle that can be inscribed in a semicircle | Function to find the area of the biggest rectangle ; the radius cannot be negative ; area of the rectangle ; Driver Code | def rectanglearea ( r ) : NEW_LINE INDENT if r < 0 : NEW_LINE INDENT return - 1 NEW_LINE DEDENT a = r * r NEW_LINE return a NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT r = 5 NEW_LINE DEDENT |
Maximum distinct lines passing through a single point | Python3 program to find maximum number of lines which can pass through a single point ; function to find maximum lines which passes through a single point ; Driver Code | import sys NEW_LINE def maxLines ( n , x1 , y1 , x2 , y2 ) : NEW_LINE INDENT s = [ ] ; NEW_LINE slope = sys . maxsize ; NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( x1 [ i ] == x2 [ i ] ) : NEW_LINE INDENT slope = sys . maxsize ; NEW_LINE DEDENT else : NEW_LINE INDENT slope = ( y2 [ i ] - y1 [ i ] ) * 1.0 / ( x... |
Find area of parallelogram if vectors of two adjacent sides are given | Python code to calculate area of parallelogram if vectors of 2 adjacent sides are given ; Function to calculate area of parallelogram ; driver code | import math NEW_LINE def area ( x1 , y1 , z1 , x2 , y2 , z2 ) : NEW_LINE INDENT area = math . sqrt ( ( y1 * z2 - y2 * z1 ) ** 2 + ( x1 * z2 - x2 * z1 ) ** 2 + ( x1 * y2 - x2 * y1 ) ** 2 ) NEW_LINE return area NEW_LINE DEDENT def main ( ) : NEW_LINE INDENT x1 = 3 NEW_LINE y1 = 1 NEW_LINE z1 = - 2 NEW_LINE x2 = 1 NEW_LIN... |
Maximum possible intersection by moving centers of line segments | Function to print the maximum intersection ; Case 1 ; Case 2 ; Case 3 ; Driver Code | def max_intersection ( center , length , k ) : NEW_LINE INDENT center . sort ( ) ; NEW_LINE if ( center [ 2 ] - center [ 0 ] >= 2 * k + length ) : NEW_LINE INDENT return 0 ; NEW_LINE DEDENT elif ( center [ 2 ] - center [ 0 ] >= 2 * k ) : NEW_LINE INDENT return ( 2 * k - ( center [ 2 ] - center [ 0 ] - length ) ) ; NEW_... |
Haversine formula to find distance between two points on a sphere | Python 3 program for the haversine formula ; distance between latitudes and longitudes ; convert to radians ; apply formulae ; Driver code | import math NEW_LINE def haversine ( lat1 , lon1 , lat2 , lon2 ) : NEW_LINE INDENT dLat = ( lat2 - lat1 ) * math . pi / 180.0 NEW_LINE dLon = ( lon2 - lon1 ) * math . pi / 180.0 NEW_LINE lat1 = ( lat1 ) * math . pi / 180.0 NEW_LINE lat2 = ( lat2 ) * math . pi / 180.0 NEW_LINE a = ( pow ( math . sin ( dLat / 2 ) , 2 ) +... |
Heptagonal number | Function to find nth Heptagonal number ; Driver Code | def heptagonalNumber ( n ) : NEW_LINE INDENT return ( ( 5 * n * n ) - ( 3 * n ) ) // 2 NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT n = 2 NEW_LINE print ( heptagonalNumber ( n ) ) NEW_LINE n = 15 NEW_LINE print ( heptagonalNumber ( n ) ) NEW_LINE DEDENT |
Icosidigonal number | Function to calculate Icosidigonal number ; Formula for finding nth Icosidigonal number ; Driver Code | def icosidigonal_num ( n ) : NEW_LINE INDENT return ( 20 * n * n - 18 * n ) // 2 NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT n = 4 NEW_LINE print ( n , " th β Icosidigonal β " + " number β : β " , icosidigonal_num ( n ) ) NEW_LINE n = 8 NEW_LINE print ( n , " th β Icosidigonal β " + " number β : β... |
Hypercube Graph | function to find power of 2 ; Dricer code | def power ( n ) : NEW_LINE INDENT if n == 1 : NEW_LINE INDENT return 2 NEW_LINE DEDENT return 2 * power ( n - 1 ) NEW_LINE DEDENT n = 4 NEW_LINE print ( power ( n ) ) NEW_LINE |
Reflection of a point at 180 degree rotation of another point | Python3 Program for find the 180 degree reflection of one point around another point . ; Driver Code | def findPoint ( x1 , y1 , x2 , y2 ) : NEW_LINE INDENT print ( " ( " , 2 * x2 - x1 , " , " , 2 * y2 - y1 , " ) " ) ; NEW_LINE DEDENT x1 = 0 ; NEW_LINE y1 = 0 ; NEW_LINE x2 = 1 ; NEW_LINE y2 = 1 ; NEW_LINE findPoint ( x1 , y1 , x2 , y2 ) ; NEW_LINE |
Program to check if the points are parallel to X axis or Y axis | To check for parallel line ; checking for parallel to X and Y axis condition ; To display the output ; Driver 's Code | def parallel ( n , a ) : NEW_LINE INDENT x = True ; NEW_LINE y = True ; NEW_LINE for i in range ( n - 1 ) : NEW_LINE INDENT if ( a [ i ] [ 0 ] != a [ i + 1 ] [ 0 ] ) : NEW_LINE INDENT x = False ; NEW_LINE DEDENT if ( a [ i ] [ 1 ] != a [ i + 1 ] [ 1 ] ) : NEW_LINE INDENT y = False ; NEW_LINE DEDENT DEDENT if ( x ) : NE... |
Triangular Matchstick Number | Python program to find X - th triangular matchstick number ; Driver code | def numberOfSticks ( x ) : NEW_LINE INDENT return ( 3 * x * ( x + 1 ) ) / 2 NEW_LINE DEDENT print ( int ( numberOfSticks ( 7 ) ) ) NEW_LINE |
Total area of two overlapping rectangles | Python program to find total area of two overlapping Rectangles Returns Total Area of two overlap rectangles ; Area of 1 st Rectangle ; Area of 2 nd Rectangle ; Length of intersecting part i . e start from max ( l1 [ x ] , l2 [ x ] ) of x - coordinate and end at min ( r1 [ x ]... | def overlappingArea ( l1 , r1 , l2 , r2 ) : NEW_LINE INDENT x = 0 NEW_LINE y = 1 NEW_LINE area1 = abs ( l1 [ x ] - r1 [ x ] ) * abs ( l1 [ y ] - r1 [ y ] ) NEW_LINE area2 = abs ( l2 [ x ] - r2 [ x ] ) * abs ( l2 [ y ] - r2 [ y ] ) NEW_LINE x_dist = ( min ( r1 [ x ] , r2 [ x ] ) - max ( l1 [ x ] , l2 [ x ] ) ) NEW_LINE ... |
Area of square Circumscribed by Circle | Function to find area of square ; Radius of a circle ; Call Function to find an area of square | def find_Area ( r ) : NEW_LINE INDENT return ( 2 * r * r ) NEW_LINE DEDENT r = 3 NEW_LINE print ( " β Area β of β square β = β " , find_Area ( r ) ) NEW_LINE |
Check whether triangle is valid or not if sides are given | function to check if three sides form a triangle or not ; check condition ; driver code ; function calling and print output | def checkValidity ( a , b , c ) : NEW_LINE INDENT if ( a + b <= c ) or ( a + c <= b ) or ( b + c <= a ) : NEW_LINE INDENT return False NEW_LINE DEDENT else : NEW_LINE INDENT return True NEW_LINE DEDENT DEDENT a = 7 NEW_LINE b = 10 NEW_LINE c = 5 NEW_LINE if checkValidity ( a , b , c ) : NEW_LINE INDENT print ( " Valid ... |
Print Longest Palindromic Subsequence | Returns LCS X and Y ; Following steps build L [ m + 1 ] [ n + 1 ] in bottom up fashion . Note that L [ i ] [ j ] contains length of LCS of X [ 0. . i - 1 ] and Y [ 0. . j - 1 ] ; Following code is used to print LCS ; Create a string length index + 1 and fill it with \ 0 ; Start f... | def lcs_ ( X , Y ) : NEW_LINE INDENT m = len ( X ) NEW_LINE n = len ( Y ) NEW_LINE L = [ [ 0 ] * ( n + 1 ) ] * ( m + 1 ) NEW_LINE for i in range ( n + 1 ) : NEW_LINE INDENT for j in range ( n + 1 ) : NEW_LINE INDENT if ( i == 0 or j == 0 ) : NEW_LINE INDENT L [ i ] [ j ] = 0 ; NEW_LINE DEDENT elif ( X [ i - 1 ] == Y [ ... |
Find the Surface area of a 3D figure | Declaring the size of the matrix ; Absolute Difference between the height of two consecutive blocks ; Function To calculate the Total surfaceArea . ; Traversing the matrix . ; If we are traveling the topmost row in the matrix , we declare the wall above it as 0 as there is no wall... | M = 3 ; NEW_LINE N = 3 ; NEW_LINE def contribution_height ( current , previous ) : NEW_LINE INDENT return abs ( current - previous ) ; NEW_LINE DEDENT def surfaceArea ( A ) : NEW_LINE INDENT ans = 0 ; NEW_LINE for i in range ( N ) : NEW_LINE INDENT for j in range ( M ) : NEW_LINE INDENT up = 0 ; NEW_LINE left = 0 ; NEW... |
Program to calculate area and volume of a Tetrahedron | Python3 Program to Calculate area of tetrahedron ; ; Driver Code | import math NEW_LINE / * Utility Function * / NEW_LINE def area_of_tetrahedron ( side ) : NEW_LINE INDENT return ( math . sqrt ( 3 ) * ( side * side ) ) ; NEW_LINE DEDENT side = 3 ; NEW_LINE print ( " Area β of β Tetrahedron β = β " , round ( area_of_tetrahedron ( side ) , 4 ) ) ; NEW_LINE |
Program to calculate area and volume of a Tetrahedron | Python code to find the volume of a tetrahedron ; Function to calculate volume ; Driver Code | import math NEW_LINE def vol_tetra ( side ) : NEW_LINE INDENT volume = ( side ** 3 / ( 6 * math . sqrt ( 2 ) ) ) NEW_LINE return round ( volume , 2 ) NEW_LINE DEDENT side = 3 NEW_LINE vol = vol_tetra ( side ) NEW_LINE print ( vol ) NEW_LINE |
Counting pairs when a person can form pair with at most one | Number of ways in which participant can take part . ; Driver code | def numberOfWays ( x ) : NEW_LINE INDENT dp = [ ] NEW_LINE dp . append ( 1 ) NEW_LINE dp . append ( 1 ) NEW_LINE for i in range ( 2 , x + 1 ) : NEW_LINE INDENT dp . append ( dp [ i - 1 ] + ( i - 1 ) * dp [ i - 2 ] ) NEW_LINE DEDENT return ( dp [ x ] ) NEW_LINE DEDENT x = 3 NEW_LINE print ( numberOfWays ( x ) ) NEW_LINE |
Program to find slope of a line | Python3 program to find slope ; Function to find the slope of a straight line ; Driver code | import sys NEW_LINE def slope ( x1 , y1 , x2 , y2 ) : NEW_LINE INDENT if x1 == x2 : NEW_LINE INDENT return ( sys . maxsize ) NEW_LINE DEDENT return ( ( y2 - y1 ) / ( x2 - x1 ) ) NEW_LINE DEDENT x1 = 4 NEW_LINE y1 = 2 NEW_LINE x2 = 2 NEW_LINE y2 = 5 NEW_LINE print ( " Slope β is β : " , slope ( 4 , 2 , 2 , 5 ) ) NEW_LIN... |
Program to calculate area and perimeter of equilateral triangle | Python3 program to calculate Area and Perimeter of equilateral Triangle ; Function to calculate Area of equilateral triangle ; Function to calculate Perimeter of equilateral triangle ; Driver code | from math import * NEW_LINE def area_equilateral ( side ) : NEW_LINE INDENT area = ( sqrt ( 3 ) / 4 ) * side * side NEW_LINE print ( " Area β of β Equilateral β Triangle : β % β f " % area ) NEW_LINE DEDENT def perimeter ( side ) : NEW_LINE INDENT perimeter = 3 * side NEW_LINE print ( " Perimeter β of β Equilateral β T... |
Maximum integral co | Making set of coordinates such that any two points are non - integral distance apart ; Used to avoid duplicates in result ; Driver code | def printSet ( x , y ) : NEW_LINE INDENT arr = [ ] NEW_LINE for i in range ( min ( x , y ) + 1 ) : NEW_LINE INDENT pq = [ i , min ( x , y ) - i ] NEW_LINE arr . append ( pq ) NEW_LINE DEDENT for it in arr : NEW_LINE INDENT print ( it [ 0 ] , it [ 1 ] ) NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE I... |
Program for Volume and Surface Area of Cuboid | utility function ; driver function | def volumeCuboid ( l , h , w ) : NEW_LINE INDENT return ( l * h * w ) NEW_LINE DEDENT def surfaceAreaCuboid ( l , h , w ) : NEW_LINE INDENT return ( 2 * l * w + 2 * w * h + 2 * l * h ) NEW_LINE DEDENT l = 1 NEW_LINE h = 5 NEW_LINE w = 7 NEW_LINE print ( " Volume β = " , volumeCuboid ( l , h , w ) ) NEW_LINE print ( " T... |
Program to find Circumference of a Circle | Python3 code to find circumference of circle ; utility function ; driver function | PI = 3.1415 NEW_LINE def circumference ( r ) : NEW_LINE INDENT return ( 2 * PI * r ) NEW_LINE DEDENT print ( ' % .3f ' % circumference ( 5 ) ) NEW_LINE |
Program to check if three points are collinear | function to check if point collinear or not ; Driver Code | def collinear ( x1 , y1 , x2 , y2 , x3 , y3 ) : NEW_LINE INDENT if ( ( y3 - y2 ) * ( x2 - x1 ) == ( y2 - y1 ) * ( x3 - x2 ) ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT DEDENT x1 , x2 , x3 , y1 , y2 , y3 = 1 , 1 , 0 , 1 , 6 , 9 NEW_LINE collinear ( x1 , y... |
Number of rectangles in N * M grid | Python3 program to count number of rectangles in a n x m grid ; Driver code | def rectCount ( n , m ) : NEW_LINE INDENT return ( m * n * ( n + 1 ) * ( m + 1 ) ) // 4 NEW_LINE DEDENT n , m = 5 , 4 NEW_LINE print ( rectCount ( n , m ) ) NEW_LINE |
Number of unique rectangles formed using N unit squares | Python3 program to count rotationally equivalent rectangles with n unit squares ; height >= length is maintained ; Driver code | import math NEW_LINE def countRect ( n ) : NEW_LINE INDENT ans = 0 NEW_LINE for length in range ( 1 , int ( math . sqrt ( n ) ) + 1 ) : NEW_LINE INDENT height = length NEW_LINE while ( height * length <= n ) : NEW_LINE INDENT ans += 1 NEW_LINE height += 1 NEW_LINE DEDENT DEDENT return ans NEW_LINE DEDENT n = 5 NEW_LINE... |
Find the Missing Point of Parallelogram | Main method ; coordinates of A ; coordinates of B ; coordinates of C | if __name__ == " _ _ main _ _ " : NEW_LINE INDENT ax , ay = 5 , 0 NEW_LINE bx , by = 1 , 1 NEW_LINE cx , cy = 2 , 5 NEW_LINE print ( ax + cx - bx , " , " , ay + cy - by ) NEW_LINE DEDENT |
Represent a given set of points by the best possible straight line | function to calculate m and c that best fit points represented by x [ ] and y [ ] ; Driver main function | def bestApproximate ( x , y , n ) : NEW_LINE INDENT sum_x = 0 NEW_LINE sum_y = 0 NEW_LINE sum_xy = 0 NEW_LINE sum_x2 = 0 NEW_LINE for i in range ( 0 , n ) : NEW_LINE INDENT sum_x += x [ i ] NEW_LINE sum_y += y [ i ] NEW_LINE sum_xy += x [ i ] * y [ i ] NEW_LINE sum_x2 += pow ( x [ i ] , 2 ) NEW_LINE DEDENT m = ( float ... |
Check for star graph | define the size of incidence matrix ; def to find star graph ; initialize number of vertex with deg 1 and n - 1 ; check for S1 ; check for S2 ; check for Sn ( n > 2 ) ; Driver code | size = 4 NEW_LINE def checkStar ( mat ) : NEW_LINE INDENT global size NEW_LINE vertexD1 = 0 NEW_LINE vertexDn_1 = 0 NEW_LINE if ( size == 1 ) : NEW_LINE INDENT return ( mat [ 0 ] [ 0 ] == 0 ) NEW_LINE DEDENT if ( size == 2 ) : NEW_LINE INDENT return ( mat [ 0 ] [ 0 ] == 0 and mat [ 0 ] [ 1 ] == 1 and mat [ 1 ] [ 0 ] ==... |
Dynamic Convex hull | Adding Points to an Existing Convex Hull | Python 3 program to add given a point p to a given convext hull . The program assumes that the point of given convext hull are in anti - clockwise order . ; checks whether the point crosses the convex hull or not ; Returns the square of distance between t... | import copy NEW_LINE def orientation ( a , b , c ) : NEW_LINE INDENT res = ( ( b [ 1 ] - a [ 1 ] ) * ( c [ 0 ] - b [ 0 ] ) - ( c [ 1 ] - b [ 1 ] ) * ( b [ 0 ] - a [ 0 ] ) ) NEW_LINE if ( res == 0 ) : NEW_LINE INDENT return 0 ; NEW_LINE DEDENT if ( res > 0 ) : NEW_LINE INDENT return 1 ; NEW_LINE DEDENT return - 1 ; NEW_... |
Find all angles of a given triangle | Python3 code to find all three angles of a triangle given coordinate of all three vertices ; returns square of distance b / w two points ; Square of lengths be a2 , b2 , c2 ; length of sides be a , b , c ; From Cosine law ; Converting to degree ; printing all the angles ; Driver co... | import math NEW_LINE def lengthSquare ( X , Y ) : NEW_LINE INDENT xDiff = X [ 0 ] - Y [ 0 ] NEW_LINE yDiff = X [ 1 ] - Y [ 1 ] NEW_LINE return xDiff * xDiff + yDiff * yDiff NEW_LINE DEDENT def printAngle ( A , B , C ) : NEW_LINE INDENT a2 = lengthSquare ( B , C ) NEW_LINE b2 = lengthSquare ( A , C ) NEW_LINE c2 = lengt... |
Triangle with no point inside | Python3 program to find triangle with no point inside ; method to get square of distance between ( x1 , y1 ) and ( x2 , y2 ) ; Method prints points which make triangle with no point inside ; any point can be chosen as first point of triangle ; choose nearest point as second point of tria... | import sys NEW_LINE def getDistance ( x1 , y1 , x2 , y2 ) : NEW_LINE INDENT return ( x2 - x1 ) * ( x2 - x1 ) + ( y2 - y1 ) * ( y2 - y1 ) NEW_LINE DEDENT def triangleWithNoPointInside ( points , N ) : NEW_LINE INDENT first = 0 NEW_LINE second = 0 NEW_LINE third = 0 NEW_LINE minD = sys . maxsize NEW_LINE for i in range (... |
Minimum steps to minimize n as per given condition | A tabulation based solution in Python3 ; driver program | def getMinSteps ( n ) : NEW_LINE INDENT table = [ 0 ] * ( n + 1 ) NEW_LINE for i in range ( n + 1 ) : NEW_LINE INDENT table [ i ] = n - i NEW_LINE DEDENT for i in range ( n , 0 , - 1 ) : NEW_LINE INDENT if ( not ( i % 2 ) ) : NEW_LINE INDENT table [ i // 2 ] = min ( table [ i ] + 1 , table [ i // 2 ] ) NEW_LINE DEDENT ... |
Minimize swaps required to make all prime | Python program for the above approach ; Create a boolean array " prime [ 0 . . n ] " and initialize all entries it as true . A value in prime [ i ] will finally be false if i is Not a prime , else true . ; If prime [ p ] is not changed , then it is a prime ; Update all multip... | import math NEW_LINE mxn = 10000 + 1 NEW_LINE prime = [ True for _ in range ( mxn + 1 ) ] NEW_LINE def SieveOfEratosthenes ( ) : NEW_LINE INDENT global prime NEW_LINE for p in range ( 2 , int ( math . sqrt ( mxn ) ) + 1 ) : NEW_LINE INDENT if ( prime [ p ] == True ) : NEW_LINE INDENT for i in range ( p * p , mxn + 1 , ... |
Find the size of Largest Subset with positive Bitwise AND | Function to find the largest possible subset having Bitwise AND positive ; Stores the number of set bits at each bit position ; Traverse the given array arr [ ] ; Current bit position ; Loop till array element becomes zero ; If the last bit is set ; Increment ... | def largestSubset ( a , N ) : NEW_LINE INDENT bit = [ 0 for i in range ( 32 ) ] NEW_LINE for i in range ( N ) : NEW_LINE INDENT x = 31 NEW_LINE while ( a [ i ] > 0 ) : NEW_LINE INDENT if ( a [ i ] & 1 == 1 ) : NEW_LINE INDENT bit [ x ] += 1 NEW_LINE DEDENT a [ i ] = a [ i ] >> 1 NEW_LINE x -= 1 NEW_LINE DEDENT DEDENT p... |
Maximum element in connected component of given node for Q queries | Function to perform the find operation to find the parent of a disjoint set ; FUnction to perform union operation of disjoint set union ; If the rank are the same ; Update the maximum value ; Function to find the maximum element of the set which belon... | def Find ( parent , a ) : NEW_LINE INDENT if ( parent [ parent [ a ] ] != parent [ a ] ) : NEW_LINE INDENT parent [ a ] = findParent ( parent , parent [ a ] ) NEW_LINE DEDENT return parent [ a ] NEW_LINE DEDENT def Union ( parent , rank , maxValue , a , b ) : NEW_LINE INDENT a = Find ( parent , a ) NEW_LINE b = Find ( ... |
Maximum sum of segments among all segments formed in array after Q queries | Python 3 program for the above approach ; Stores the maximum integer of the sets for each query ; Function to perform the find operation of disjoint set union ; Function to perform the Union operation of disjoint set union ; Find the parent of... | import sys NEW_LINE maxAns = - sys . maxsize - 1 NEW_LINE def Find ( parent , a ) : NEW_LINE INDENT if ( parent [ a ] == a ) : NEW_LINE INDENT return a NEW_LINE DEDENT return Find ( parent , parent [ a ] ) NEW_LINE DEDENT def Union ( parent , rank , setSum , a , b ) : NEW_LINE INDENT a = Find ( parent , a ) NEW_LINE b ... |
ZigZag Level Order Traversal of an N | Structure of a tree node ; Function to create a new node ; Function to perform zig zag traversal of the given tree ; Stores the vectors containing nodes in each level of tree respectively ; Create a queue for BFS ; Enqueue Root of the tree ; Standard Level Order Traversal code usi... | class Node : NEW_LINE INDENT def __init__ ( self , key ) : NEW_LINE INDENT self . val = key NEW_LINE self . child = [ ] NEW_LINE DEDENT DEDENT def newNode ( key ) : NEW_LINE INDENT temp = Node ( key ) NEW_LINE return temp NEW_LINE DEDENT def zigzagLevelOrder ( root ) : NEW_LINE INDENT if ( root == None ) : NEW_LINE IND... |
Minimum length paths between 1 to N including each node | Function to calculate the distances from node 1 to N ; Vector to store our edges ; Storing the edgees in the Vector ; Initialize queue ; BFS from first node using queue ; Pop from queue ; Traversing its adjacency list ; Initialize queue ; BFS from last node usin... | def minDisIncludingNode ( n , m , edges ) : NEW_LINE INDENT g = [ [ ] for i in range ( 10005 ) ] NEW_LINE for i in range ( m ) : NEW_LINE INDENT a = edges [ i ] [ 0 ] - 1 NEW_LINE b = edges [ i ] [ 1 ] - 1 NEW_LINE g [ a ] . append ( b ) NEW_LINE g [ b ] . append ( a ) NEW_LINE DEDENT q = [ ] NEW_LINE q . append ( [ 0 ... |
Check if possible to make Array sum equal to Array product by replacing exactly one element | Function to check if it is possible to form an array whose sum and the product is the same or not ; Find the sum of the array ; ; Find the product of the array ; Check a complete integer y for every x ; If got such y ; If no ... | def canPossibleReplacement ( N , arr ) : NEW_LINE INDENT S = sum ( arr ) NEW_LINE DEDENT / * Iterate through all elements and NEW_LINE INDENT add them to sum * / NEW_LINE P = 1 NEW_LINE for i in arr : NEW_LINE INDENT P *= i NEW_LINE DEDENT for x in arr : NEW_LINE INDENT y = ( S - x ) // ( P / x - 1 ) NEW_LINE if ( S - ... |
Check if all the digits of the given number are same | Python3 program for the above approach ; Function to check if all the digits in the number N is the same or not ; Get the length of N ; Form the number M of the type K * 111. . . where K is the rightmost digit of N ; Check if the numbers are equal ; Otherwise ; Dri... | import math NEW_LINE def checkSameDigits ( N ) : NEW_LINE INDENT length = int ( math . log10 ( N ) ) + 1 ; NEW_LINE M = ( int ( math . pow ( 10 , length ) ) - 1 ) // ( 10 - 1 ) ; NEW_LINE M *= N % 10 ; NEW_LINE if ( M == N ) : NEW_LINE INDENT return " Yes " ; NEW_LINE DEDENT return " No " ; NEW_LINE DEDENT if __name__ ... |
Maximize sum of path from the Root to a Leaf node in N | Stores the maximum sum of a path ; Structure of a node in the tree ; Utility function to create a new node in the tree ; Recursive function to calculate the maximum sum in a path using DFS ; If current node is a leaf node ; Traversing all children of the current ... | maxSumPath = 0 NEW_LINE class Node : NEW_LINE INDENT def __init__ ( self , key ) : NEW_LINE INDENT self . val = key NEW_LINE self . child = [ ] NEW_LINE DEDENT DEDENT def newNode ( key ) : NEW_LINE INDENT temp = Node ( key ) NEW_LINE return temp NEW_LINE DEDENT def DFS ( root , Sum ) : NEW_LINE INDENT global maxSumPath... |
Count of even sum triplets in the array for Q range queries | Function to count number of triplets with even sum in range l , r for each query ; Initialization of array ; Initialization of variables ; Traversing array ; If element is odd ; If element is even ; Storing count of even and odd till each i ; Traversing each... | def countTriplets ( size , queries , arr , Q ) : NEW_LINE INDENT arr_even = [ 0 for i in range ( size + 1 ) ] NEW_LINE arr_odd = [ 0 for i in range ( size + 1 ) ] NEW_LINE even = 0 NEW_LINE odd = 0 NEW_LINE arr_even [ 0 ] = 0 NEW_LINE arr_odd [ 0 ] = 0 NEW_LINE for i in range ( size ) : NEW_LINE INDENT if ( arr [ i ] %... |
Maximize the rightmost element of an array in k operations in Linear Time | Function to calculate maximum value of Rightmost element ; Calculating maximum value of Rightmost element ; Checking if arr [ i ] is operationable ; Performing operation of i - th element ; Decreasing the value of k by 1 ; Printing rightmost el... | def maxRightmostElement ( N , k , p , arr ) : NEW_LINE INDENT while ( k ) : NEW_LINE INDENT for i in range ( N - 2 , - 1 , - 1 ) : NEW_LINE INDENT if ( arr [ i ] >= p ) : NEW_LINE INDENT arr [ i ] = arr [ i ] - p NEW_LINE arr [ i + 1 ] = arr [ i + 1 ] + p NEW_LINE break NEW_LINE DEDENT DEDENT k = k - 1 NEW_LINE DEDENT ... |
Mean of minimum of all possible K | Function to find the value of nCr ; Base Case ; Find nCr recursively ; Function to find the expected minimum values of all the subsets of size K ; Find the factorials that will be used later ; Find the factorials ; Total number of subsets ; Stores the sum of minimum over all possible... | def nCr ( n , r , f ) : NEW_LINE INDENT if ( n < r ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT return f [ n ] / ( f [ r ] * f [ n - r ] ) NEW_LINE DEDENT def findMean ( N , X ) : NEW_LINE INDENT f = [ 0 for i in range ( N + 1 ) ] NEW_LINE f [ 0 ] = 1 NEW_LINE for i in range ( 1 , N + 1 , 1 ) : NEW_LINE INDENT f [ i ] ... |
Maximize count of odd | To find maximum number of pairs in array with conversion of at most one element ; Initialize count of even elements ; Initialize count of odd elements ; If current number is even then increment x by 1 ; If current number is odd then increment y by 1 ; Initialize the answer by min ( x , y ) ; If ... | def maximumNumberofpairs ( n , arr ) : NEW_LINE INDENT x = 0 NEW_LINE y = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( arr [ i ] % 2 == 0 ) : NEW_LINE INDENT x += 1 NEW_LINE DEDENT else : NEW_LINE INDENT y += 1 NEW_LINE DEDENT DEDENT answer = min ( x , y ) NEW_LINE if ( abs ( x - y ) >= 2 ) : NEW_LINE INDENT ... |
Sum of product of all unordered pairs in given range with update queries | Function to calculate the Pairwise Product Sum in range from L to R ; Loop to iterate over all possible pairs from L to R ; Print answer ; Function to update the Array element at index P to X ; Update the value at Pth index in the array ; Functi... | def pairwiseProductSum ( a , l , r ) : NEW_LINE INDENT sum = 0 NEW_LINE for j in range ( l - 1 , r , 1 ) : NEW_LINE INDENT for k in range ( j + 1 , r , 1 ) : NEW_LINE INDENT sum += ( a [ j ] * a [ k ] ) ; NEW_LINE DEDENT DEDENT print ( sum ) NEW_LINE DEDENT def updateArray ( a , p , x ) : NEW_LINE INDENT a [ p - 1 ] = ... |
Check if final remainder is present in original Array by reducing it based on given conditions | Python program to implement above approach ; copying original array ; loop till length of array become 2. ; find middle element ; pop element from front and rear ; find remainder ; append remainder to a ; now since length o... | def Reduced ( a , n ) : NEW_LINE INDENT original_array = a [ : ] NEW_LINE while len ( a ) != 2 : NEW_LINE INDENT mid = len ( a ) // 2 NEW_LINE mid_ele = a [ mid ] NEW_LINE start = a . pop ( 0 ) NEW_LINE end = a . pop ( ) NEW_LINE rmd = ( start * end ) % mid_ele NEW_LINE a . append ( rmd ) NEW_LINE DEDENT remainder = ( ... |
Find two numbers from their sum and OR | Python 3 program for the above approach ; Function to find the two integers from the given sum and Bitwise OR value ; Check if Z is non negative ; Iterate through all the bits ; Find the kth bit of A & B ; Find the kth bit of A | B ; If bit1 = 1 and bit2 = 0 , then there will be... | MaxBit = 32 NEW_LINE def possiblePair ( X , Y ) : NEW_LINE INDENT Z = Y - X NEW_LINE if ( Z < 0 ) : NEW_LINE INDENT print ( " - 1" ) NEW_LINE return 0 NEW_LINE DEDENT for k in range ( MaxBit ) : NEW_LINE INDENT bit1 = ( Z >> k ) & 1 NEW_LINE bit2 = ( Z >> k ) & 1 NEW_LINE if ( bit1 == 1 and bit2 == 0 ) : NEW_LINE INDEN... |
Maximum frequencies in each M | Function to find the frequency of the most common element in each M length subarrays ; Stores frequency of array element ; Stores the maximum frequency ; Iterate for the first sub - array and store the maximum ; Print the maximum frequency for the first subarray ; Iterate over the range ... | def maxFrequencySubarrayUtil ( A , N , M ) : NEW_LINE INDENT i = 0 NEW_LINE m = { } NEW_LINE val = 0 NEW_LINE while ( i < M ) : NEW_LINE INDENT if A [ i ] in m : NEW_LINE INDENT m [ A [ i ] ] += 1 NEW_LINE DEDENT else : NEW_LINE INDENT m [ A [ i ] ] = 1 NEW_LINE DEDENT val = max ( val , m [ A [ i ] ] ) NEW_LINE i += 1 ... |
Maximum number of pairs of distinct array elements possible by including each element in only one pair | Function to count the maximum number of pairs having different element from the given array ; Stores the frequency of array element ; Stores maximum count of pairs ; Increasing the frequency of every element ; Store... | def maximumPairs ( a , n ) : NEW_LINE INDENT freq = { } NEW_LINE count = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT if a [ i ] in freq : NEW_LINE INDENT freq [ a [ i ] ] += 1 NEW_LINE DEDENT else : NEW_LINE INDENT freq [ a [ i ] ] = 1 NEW_LINE DEDENT DEDENT pq = [ ] NEW_LINE for key , value in freq . items ( ) :... |
Generate an N | Python3 program for above approach ; Function to print target array ; Sort the given array ; Seeking for index of elements with minimum diff . ; Seeking for index ; To store target array ; Copying element ; Copying remaining element ; Printing target array ; Driver Code ; Given Input ; Function Call | import sys NEW_LINE def printArr ( arr , n ) : NEW_LINE INDENT arr . sort ( ) NEW_LINE minDifference = sys . maxsize NEW_LINE minIndex = - 1 NEW_LINE for i in range ( 1 , n , 1 ) : NEW_LINE INDENT if ( minDifference > abs ( arr [ i ] - arr [ i - 1 ] ) ) : NEW_LINE INDENT minDifference = abs ( arr [ i ] - arr [ i - 1 ] ... |
Construct a Perfect Binary Tree from Preorder Traversal | Structure of the tree ; Function to create a new node with the value val ; Return the newly created node ; Function to create the Perfect Binary Tree ; If preStart > preEnd return NULL ; Initialize root as pre [ preStart ] ; If the only node is left , then retur... | class Node : NEW_LINE INDENT def __init__ ( self , val ) : NEW_LINE INDENT self . data = val NEW_LINE self . left = None NEW_LINE self . right = None NEW_LINE DEDENT DEDENT def getNewNode ( val ) : NEW_LINE INDENT newNode = Node ( val ) NEW_LINE return newNode NEW_LINE DEDENT def buildPerfectBT_helper ( preStart , preE... |
Minimize operations to convert each node of N | Create adjacency list ; Function to add an edges in graph ; Function to perform the DFS of graph recursively from a given vertex u ; Check for the condition for the flipping of node 's initial value ; Traverse all the children of the current source node u ; Swap foo and f... | N = 3 NEW_LINE adj = [ ] NEW_LINE for i in range ( N + 1 ) : NEW_LINE INDENT adj . append ( [ ] ) NEW_LINE DEDENT visited = [ ] NEW_LINE ans = 0 NEW_LINE def addEdges ( u , v ) : NEW_LINE INDENT global adj NEW_LINE adj [ u ] . append ( v ) NEW_LINE adj [ v ] . append ( u ) NEW_LINE DEDENT def DFSUtil ( u , foo , foo1 ,... |
Minimum number of moves to make M and N equal by repeatedly adding any divisor of number to itself except 1 and the number | Function to find the minimum number of moves to make N and M equal . ; Array to maintain the numbers included . ; Pair of vertex , count ; Run bfs from N ; If we reached goal ; Iterate in the ran... | def countOperations ( N , M ) : NEW_LINE INDENT visited = [ False ] * ( 100001 ) NEW_LINE Q = [ ] NEW_LINE Q . append ( [ N , 0 ] ) NEW_LINE visited [ N ] = True NEW_LINE while ( len ( Q ) > 0 ) : NEW_LINE INDENT aux = Q [ 0 ] [ 0 ] NEW_LINE cont = Q [ 0 ] [ 1 ] NEW_LINE Q . pop ( 0 ) NEW_LINE if ( aux == M ) : NEW_LIN... |
Finding Astronauts from different countries | Function to perform the DFS Traversal to find the count of connected components ; Marking vertex visited ; DFS call to neighbour vertices ; If the current node is not visited , then recursively call DFS ; Function to find the number of ways to choose two astronauts from the... | adj = [ ] NEW_LINE visited = [ ] NEW_LINE num = 0 NEW_LINE def dfs ( v ) : NEW_LINE INDENT global adj , visited , num NEW_LINE visited [ v ] = True NEW_LINE num += 1 NEW_LINE for i in range ( len ( adj [ v ] ) ) : NEW_LINE INDENT if ( not visited [ adj [ v ] [ i ] ] ) : NEW_LINE INDENT dfs ( adj [ v ] [ i ] ) NEW_LINE ... |
Count of Perfect Numbers in given range for Q queries | python 3 program for the above approach ; Function to check whether a number is perfect Number ; Stores sum of divisors ; Itearate over the range [ 2 , sqrt ( N ) ] ; If sum of divisors is equal to N , then N is a perfect number ; Function to find count of perfect... | MAX = 100005 NEW_LINE from math import sqrt NEW_LINE def isPerfect ( N ) : NEW_LINE INDENT sum = 1 NEW_LINE for i in range ( 2 , int ( sqrt ( N ) ) + 1 , 1 ) : NEW_LINE INDENT if ( N % i == 0 ) : NEW_LINE INDENT if ( i * i != N ) : NEW_LINE INDENT sum = sum + i + N // i NEW_LINE DEDENT else : NEW_LINE INDENT sum = sum ... |
Find any possible two coordinates of Rectangle whose two coordinates are given | Function to find the remaining two rectangle coordinates ; Pairs to store the position of given two coordinates of the rectangle . ; Pairs to store the remaining two coordinates of the rectangle . ; Traverse through matrix and find pairs p... | def Create_Rectangle ( arr , n ) : NEW_LINE INDENT for i in range ( n ) : NEW_LINE INDENT arr [ i ] = [ i for i in arr [ i ] ] NEW_LINE DEDENT p1 = [ - 1 , - 1 ] NEW_LINE p2 = [ - 1 , - 1 ] NEW_LINE p3 = [ ] NEW_LINE p4 = [ ] NEW_LINE for i in range ( n ) : NEW_LINE INDENT for j in range ( n ) : NEW_LINE INDENT if ( ar... |
Sum of all the prime divisors of a number | Set 2 | Python3 program for the above approach ; Function to find sum of prime divisors of the given number N ; Add the number 2 if it divides N ; Traverse the loop from [ 3 , sqrt ( N ) ] ; If i divides N , add i and divide N ; This condition is to handle the case when N is ... | import math NEW_LINE def SumOfPrimeDivisors ( n ) : NEW_LINE INDENT sum = 0 NEW_LINE if n % 2 == 0 : NEW_LINE INDENT sum += 2 NEW_LINE DEDENT while n % 2 == 0 : NEW_LINE INDENT n //= 2 NEW_LINE DEDENT k = int ( math . sqrt ( n ) ) NEW_LINE for i in range ( 3 , k + 1 , 2 ) : NEW_LINE INDENT if n % i == 0 : NEW_LINE INDE... |
Minimum insertions to form a palindrome | DP | A Naive recursive program to find minimum number insertions needed to make a string palindrome ; Recursive function to find minimum number of insertions ; Base Cases ; Check if the first and last characters are same . On the basis of the comparison result , decide which su... | import sys NEW_LINE def findMinInsertions ( str , l , h ) : NEW_LINE INDENT if ( l > h ) : NEW_LINE INDENT return sys . maxsize NEW_LINE DEDENT if ( l == h ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT if ( l == h - 1 ) : NEW_LINE INDENT return 0 if ( str [ l ] == str [ h ] ) else 1 NEW_LINE DEDENT if ( str [ l ] == str... |
Count bases which contains a set bit as the Most Significant Bit in the representation of N | Python 3 program for the above approach ; Function to count bases having MSB of N as a set bit ; Store the required count ; Iterate over the range [ 2 , N ] ; Store the MSB of N ; If MSB is 1 , then increment the count by 1 ; ... | import math NEW_LINE def countOfBase ( N ) : NEW_LINE INDENT count = 0 NEW_LINE for i in range ( 2 , N + 1 ) : NEW_LINE INDENT highestPower = int ( math . log ( N ) / math . log ( i ) ) NEW_LINE firstDigit = int ( N / int ( math . pow ( i , highestPower ) ) ) NEW_LINE if ( firstDigit == 1 ) : NEW_LINE INDENT count += 1... |
K | Function to find the kth digit from last in an integer n ; If k is less than equal to 0 ; Convert integer into string ; If k is greater than length of the temp ; Print the k digit from last ; Driver code ; Given Input ; Function call | def kthDigitFromLast ( n , k ) : NEW_LINE INDENT if ( k <= 0 ) : NEW_LINE INDENT print ( - 1 ) NEW_LINE return NEW_LINE DEDENT temp = str ( n ) NEW_LINE if ( k > len ( temp ) ) : NEW_LINE INDENT print ( - 1 ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( ord ( temp [ len ( temp ) - k ] ) - ord ( '0' ) ) NEW_LINE DEDEN... |
Count ways to split array into three non | Function to count ways to split array into three subarrays with equal Bitwise XOR ; Stores the XOR value of arr [ ] ; Update the value of arr_xor ; Stores the XOR value of prefix and suffix array respectively ; Stores the ending points of all the required prefix arrays ; Store... | def countWays ( arr , N ) : NEW_LINE INDENT arr_xor = 0 NEW_LINE for i in range ( N ) : NEW_LINE INDENT arr_xor ^= arr [ i ] NEW_LINE DEDENT pref_xor , suff_xor = 0 , 0 NEW_LINE pref_ind = [ ] NEW_LINE suff_inds = [ 0 ] * ( N + 1 ) NEW_LINE for i in range ( N ) : NEW_LINE INDENT pref_xor ^= arr [ i ] NEW_LINE if ( pref... |
Count pairs up to N having sum equal to their XOR | 2D array for memoization ; Recursive Function to count pairs ( x , y ) such that x + y = x ^ y ; If the string is traversed completely ; If the current subproblem is already calculated ; If bound = 1 and s [ i ] = = '0' , only ( 0 , 0 ) can be placed ; Otherwise ; Pla... | dp = [ [ - 1 for i in range ( 2 ) ] for j in range ( 1000 ) ] NEW_LINE def IsSumEqualsXor ( i , n , bound , s ) : NEW_LINE INDENT if ( i == n ) : NEW_LINE INDENT return 1 NEW_LINE DEDENT if ( dp [ i ] [ bound ] != - 1 ) : NEW_LINE INDENT return dp [ i ] [ bound ] NEW_LINE DEDENT ans = 0 NEW_LINE if ( bound and s [ i ] ... |
Mean of fourth powers of first N natural numbers | Function to find the average of the fourth power of first N natural numbers ; Stores the sum of the fourth powers of first N natural numbers ; Calculate the sum of fourth power ; Return the average ; Driver Code | def findAverage ( N ) : NEW_LINE INDENT S = 0 NEW_LINE for i in range ( 1 , N + 1 ) : NEW_LINE INDENT S += i * i * i * i NEW_LINE DEDENT return round ( S / N , 4 ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 3 NEW_LINE print ( findAverage ( N ) ) NEW_LINE DEDENT |
Construct a graph from given degrees of all vertices | A function to print the adjacency matrix . ; n is number of vertices ; For each pair of vertex decrement the degree of both vertex . ; Print the result in specified form ; Driver Code | def printMat ( degseq , n ) : NEW_LINE INDENT mat = [ [ 0 ] * n for i in range ( n ) ] NEW_LINE for i in range ( n ) : NEW_LINE INDENT for j in range ( i + 1 , n ) : NEW_LINE INDENT if ( degseq [ i ] > 0 and degseq [ j ] > 0 ) : NEW_LINE INDENT degseq [ i ] -= 1 NEW_LINE degseq [ j ] -= 1 NEW_LINE mat [ i ] [ j ] = 1 N... |
Decimal equivalent of concatenation of absolute difference of floor and rounded | Function to find the decimal equivalent of the new binary array constructed from absolute decimal of floor and the round - off values ; Traverse the givenarray from the end ; Stores the absolute difference between floor and round - off ea... | def findDecimal ( arr , N ) : NEW_LINE INDENT power = 0 ; NEW_LINE result = 0 ; NEW_LINE for i in range ( N - 1 , - 1 , - 1 ) : NEW_LINE INDENT bit = abs ( int ( arr [ i ] ) - round ( arr [ i ] ) ) ; NEW_LINE if ( bit ) : NEW_LINE INDENT result += pow ( 2 , power ) ; NEW_LINE DEDENT power += 1 ; NEW_LINE DEDENT print (... |
Calculate money placed in boxes after N days based on given conditions | Function to find the total money placed in boxes after N days ; Stores the total money ; Iterate for N days ; Adding the Week number ; Adding previous amount + 1 ; Return the total amount ; Input ; Function call to find total money placed | def totalMoney ( N ) : NEW_LINE INDENT ans = 0 NEW_LINE for i in range ( 0 , N ) : NEW_LINE INDENT ans += i / 7 NEW_LINE ans += ( i % 7 + 1 ) NEW_LINE DEDENT return ans NEW_LINE DEDENT N = 15 NEW_LINE print ( totalMoney ( N ) ) NEW_LINE |
Sum of absolute differences of indices of occurrences of each array element | Set 2 | Stores the count of occurrences and previous index of every element ; Constructor ; Function to calculate the sum of absolute differences of indices of occurrences of array element ; Stores the count of elements and their previous ind... | class pair : NEW_LINE INDENT def __init__ ( self , count , prevIndex ) : NEW_LINE INDENT self . count = count ; NEW_LINE self . prevIndex = prevIndex ; NEW_LINE DEDENT DEDENT def findSum ( arr , n ) : NEW_LINE INDENT map = { } ; NEW_LINE left = [ 0 for i in range ( n ) ] ; NEW_LINE right = [ 0 for i in range ( n ) ] ; ... |
Convert a number to another by dividing by its factor or removing first occurrence of a digit from an array | Python3 program for the above approach ; Function to check if a digit x is present in the number N or not ; Convert N to string ; Traverse the num ; Return first occurrence of the digit x ; Function to remove t... | from collections import deque NEW_LINE def isPresent ( n , x ) : NEW_LINE INDENT num = str ( n ) NEW_LINE for i in range ( len ( num ) ) : NEW_LINE INDENT if ( ( ord ( num [ i ] ) - ord ( '0' ) ) == x ) : NEW_LINE INDENT return i NEW_LINE DEDENT DEDENT return - 1 NEW_LINE DEDENT def removeDigit ( n , index ) : NEW_LINE... |
Prime triplets consisting of values up to N having difference between two elements equal to the third | Python3 program for the above approach ; Stores 1 and 0 at indices which are prime and non - prime respectively ; Function to find all prime numbers from the range [ 0 , N ] ; Iterate over the range [ 2 , sqrt ( N ) ... | from math import sqrt NEW_LINE prime = [ True for i in range ( 100000 ) ] NEW_LINE def SieveOfEratosthenes ( n ) : NEW_LINE INDENT for p in range ( 2 , int ( sqrt ( n ) ) + 1 , 1 ) : NEW_LINE INDENT if ( prime [ p ] == True ) : NEW_LINE INDENT for i in range ( p * p , n + 1 , p ) : NEW_LINE INDENT prime [ i ] = False N... |
Smallest number which is not coprime with any element of an array | Python 3 program for the above approach ; Function check if a number is prime or not ; Corner cases ; Check if n is divisible by 2 or 3 ; Check for every 6 th number . The above checking allows to skip middle 5 numbers ; Function to store primes in an ... | MAX = 50 NEW_LINE import sys NEW_LINE from math import sqrt , gcd NEW_LINE def isPrime ( n ) : NEW_LINE INDENT if ( n <= 1 ) : NEW_LINE INDENT return False NEW_LINE DEDENT if ( n <= 3 ) : NEW_LINE INDENT return True NEW_LINE DEDENT if ( n % 2 == 0 or n % 3 == 0 ) : NEW_LINE INDENT return False NEW_LINE DEDENT for i in ... |
Count numbers from a given range that can be expressed as sum of digits raised to the power of count of digits | Python 3 program for the above approach ; Function to check if a number N can be expressed as sum of its digits raised to the power of the count of digits ; Stores the number of digits ; Stores the resultant... | R = 100005 NEW_LINE arr = [ 0 for i in range ( R ) ] NEW_LINE def canExpress ( N ) : NEW_LINE INDENT temp = N NEW_LINE n = 0 NEW_LINE while ( N != 0 ) : NEW_LINE INDENT N //= 10 NEW_LINE n += 1 NEW_LINE DEDENT N = temp NEW_LINE sum = 0 NEW_LINE while ( N != 0 ) : NEW_LINE INDENT sum += pow ( N % 10 , n ) NEW_LINE N //=... |
Queries to calculate sum of the path from root to a given node in given Binary Tree | Function to find the sum of the path from root to the current node ; Sum of nodes in the path ; Iterate until root is reached ; Update the node value ; Print the resultant sum ; Function to print the path sum for each query ; Traverse... | def sumOfNodeInAPath ( node_value ) : NEW_LINE INDENT sum_of_node = 0 NEW_LINE while ( node_value ) : NEW_LINE INDENT sum_of_node += node_value NEW_LINE node_value //= 2 NEW_LINE DEDENT print ( sum_of_node , end = " β " ) NEW_LINE DEDENT def findSum ( Q ) : NEW_LINE INDENT for i in range ( len ( Q ) ) : NEW_LINE INDENT... |
Minimum removals required to make frequency of all remaining array elements equal | Python 3 program for the above approach ; Function to count the minimum removals required to make frequency of all array elements equal ; Stores frequency of all array elements ; Traverse the array ; Stores all the frequencies ; Travers... | from collections import defaultdict NEW_LINE def minDeletions ( arr , N ) : NEW_LINE INDENT freq = defaultdict ( int ) NEW_LINE for i in range ( N ) : NEW_LINE INDENT freq [ arr [ i ] ] += 1 NEW_LINE DEDENT v = [ ] NEW_LINE for z in freq . keys ( ) : NEW_LINE INDENT v . append ( freq [ z ] ) NEW_LINE DEDENT v . sort ( ... |
Check if a string is the typed name of the given name | Check if the character is vowel or not ; Returns true if ' typed ' is a typed name given str ; Traverse through all characters of str ; If current characters do not match ; If not vowel , simply move ahead in both ; Count occurrences of current vowel in str ; Coun... | def isVowel ( c ) : NEW_LINE INDENT vowel = " aeiou " NEW_LINE for i in range ( len ( vowel ) ) : NEW_LINE INDENT if ( vowel [ i ] == c ) : NEW_LINE INDENT return True NEW_LINE DEDENT DEDENT return False NEW_LINE DEDENT def printRLE ( str , typed ) : NEW_LINE INDENT n = len ( str ) NEW_LINE m = len ( typed ) NEW_LINE j... |
Determine whether a universal sink exists in a directed graph | Python3 program to find whether a universal sink exists in a directed graph ; constructor to initialize number of vertices and size of adjacency matrix ; make adjacency_matrix [ i ] [ j ] = 1 if there is an edge from i to j ; if any element in the row i is... | class Graph : NEW_LINE INDENT def __init__ ( self , vertices ) : NEW_LINE INDENT self . vertices = vertices NEW_LINE self . adjacency_matrix = [ [ 0 for i in range ( vertices ) ] for j in range ( vertices ) ] NEW_LINE DEDENT def insert ( self , s , destination ) : NEW_LINE INDENT self . adjacency_matrix [ s - 1 ] [ des... |
Reverse alternate levels of a perfect binary tree | Python3 program to reverse alternate levels of a tree A Binary Tree Node Utility function to create a new tree node ; Base cases ; Swap subtrees if level is even ; Recur for left and right subtrees ( Note : left of root1 is passed and right of root2 in first call and ... | class Node : NEW_LINE INDENT def __init__ ( self , key ) : NEW_LINE INDENT self . key = key NEW_LINE self . left = None NEW_LINE self . right = None NEW_LINE DEDENT DEDENT def preorder ( root1 , root2 , lvl ) : NEW_LINE INDENT if ( root1 == None or root2 == None ) : NEW_LINE INDENT return NEW_LINE DEDENT if ( lvl % 2 =... |
Deletion in a Binary Tree | class to create a node with data , left child and right child . ; Inorder traversal of a binary tree ; function to delete the given deepest node ( d_node ) in binary tree ; Do level order traversal until last node ; function to delete element in binary tree ; Do level order traversal to find... | class Node : NEW_LINE INDENT def __init__ ( self , data ) : NEW_LINE INDENT self . data = data NEW_LINE self . left = None NEW_LINE self . right = None NEW_LINE DEDENT DEDENT def inorder ( temp ) : NEW_LINE INDENT if ( not temp ) : NEW_LINE INDENT return NEW_LINE DEDENT inorder ( temp . left ) NEW_LINE print ( temp . d... |
Number of sink nodes in a graph | Return the number of Sink NOdes . ; Array for marking the non - sink node . ; Marking the non - sink node . ; Counting the sink nodes . ; Driver Code | def countSink ( n , m , edgeFrom , edgeTo ) : NEW_LINE INDENT mark = [ 0 ] * ( n + 1 ) NEW_LINE for i in range ( m ) : NEW_LINE INDENT mark [ edgeFrom [ i ] ] = 1 NEW_LINE DEDENT count = 0 NEW_LINE for i in range ( 1 , n + 1 ) : NEW_LINE INDENT if ( not mark [ i ] ) : NEW_LINE INDENT count += 1 NEW_LINE DEDENT DEDENT r... |
Largest subset of Graph vertices with edges of 2 or more colors | Number of vertices ; function to calculate max subset size ; set for number of vertices ; loop for deletion of vertex from set ; if subset has only 1 vertex return 0 ; for each vertex iterate and keep removing a vertix while we find a vertex with all edg... | N = 6 NEW_LINE def subsetGraph ( C ) : NEW_LINE INDENT global N NEW_LINE vertices = set ( ) NEW_LINE for i in range ( N ) : NEW_LINE INDENT vertices . add ( i ) NEW_LINE DEDENT while ( len ( vertices ) != 0 ) : NEW_LINE INDENT if ( len ( vertices ) == 1 ) : NEW_LINE INDENT return 1 NEW_LINE DEDENT someone_removed = Fal... |
Count number of edges in an undirected graph | Adjacency list representation of graph ; add edge to graph ; Returns count of edge in undirected graph ; traverse all vertex ; add all edge that are linked to the current vertex ; The count of edge is always even because in undirected graph every edge is connected twice be... | class Graph : NEW_LINE INDENT def __init__ ( self , V ) : NEW_LINE INDENT self . V = V NEW_LINE self . adj = [ [ ] for i in range ( V ) ] NEW_LINE DEDENT def addEdge ( self , u , v ) : NEW_LINE INDENT self . adj [ u ] . append ( v ) NEW_LINE self . adj [ v ] . append ( u ) NEW_LINE DEDENT def countEdges ( self ) : NEW_... |
Two Clique Problem ( Check if Graph can be divided in two Cliques ) | Python3 program to find out whether a given graph can be converted to two Cliques or not . ; This function returns true if subgraph reachable from src is Bipartite or not . ; Create a queue ( FIFO ) of vertex numbers and enqueue source vertex for BFS... | from queue import Queue NEW_LINE def isBipartiteUtil ( G , src , colorArr ) : NEW_LINE INDENT global V NEW_LINE colorArr [ src ] = 1 NEW_LINE q = Queue ( ) NEW_LINE q . put ( src ) NEW_LINE while ( not q . empty ( ) ) : NEW_LINE INDENT u = q . get ( ) NEW_LINE for v in range ( V ) : NEW_LINE INDENT if ( G [ u ] [ v ] a... |
Check whether given degrees of vertices represent a Graph or Tree | Function returns true for tree false for graph ; Find sum of all degrees ; It is tree if sum is equal to 2 ( n - 1 ) ; main | def check ( degree , n ) : NEW_LINE INDENT deg_sum = sum ( degree ) NEW_LINE if ( 2 * ( n - 1 ) == deg_sum ) : NEW_LINE INDENT return True NEW_LINE DEDENT else : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT n = 5 NEW_LINE degree = [ 2 , 3 , 1 , 1 , 1 ] ; NEW_LINE if ( check ( degree , n ) ) : NEW_LINE INDENT pri... |
Finding minimum vertex cover size of a graph using binary search | A Python3 program to find size of minimum vertex cover using Binary Search ; Global array to store the graph Note : since the array is global , all the elements are 0 initially ; Returns true if there is a possible subSet of size ' k ' that can be a ver... | maxn = 25 NEW_LINE gr = [ [ None ] * maxn for i in range ( maxn ) ] NEW_LINE def isCover ( V , k , E ) : NEW_LINE INDENT Set = ( 1 << k ) - 1 NEW_LINE limit = ( 1 << V ) NEW_LINE vis = [ [ None ] * maxn for i in range ( maxn ) ] NEW_LINE while ( Set < limit ) : NEW_LINE INDENT vis = [ [ 0 ] * maxn for i in range ( maxn... |
Morris traversal for Preorder | Python program for Morris Preorder traversal A binary tree Node ; Preorder traversal without recursion and without stack ; If left child is null , print the current node data . And , update the current pointer to right child . ; Find the inorder predecessor ; If the right child of inorde... | class Node : NEW_LINE INDENT def __init__ ( self , data ) : NEW_LINE INDENT self . data = data NEW_LINE self . left = None NEW_LINE self . right = None NEW_LINE DEDENT DEDENT def MorrisTraversal ( root ) : NEW_LINE INDENT curr = root NEW_LINE while curr : NEW_LINE INDENT if curr . left is None : NEW_LINE INDENT print (... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.