text
stringlengths 17
3.65k
| code
stringlengths 70
5.84k
|
---|---|
Boyer Moore Algorithm for Pattern Searching | Python3 Program for Bad Character Heuristic of Boyer Moore String Matching Algorithm ; The preprocessing function for Boyer Moore 's bad character heuristic ; Initialize all occurrence as - 1 ; Fill the actual value of last occurrence ; A pattern searching function that uses Bad Character Heuristic of Boyer Moore Algorithm ; create the bad character list by calling the preprocessing function badCharHeuristic ( ) for given pattern ; s is shift of the pattern with respect to text ; there are n - m + 1 potential allignments ; Keep reducing index j of pattern while characters of pattern and text are matching at this shift s ; If the pattern is present at current shift , then index j will become - 1 after the above loop ; Shift the pattern so that the next character in text aligns with the last occurrence of it in pattern . The condition s + m < n is necessary for the case when pattern occurs at the end of text ; Shift the pattern so that the bad character in text aligns with the last occurrence of it in pattern . The max function is used to make sure that we get a positive shift . We may get a negative shift if the last occurrence of bad character in pattern is on the right side of the current character . ; Driver program to test above function | NO_OF_CHARS = 256 NEW_LINE def badCharHeuristic ( string , size ) : NEW_LINE INDENT badChar = [ - 1 ] * NO_OF_CHARS NEW_LINE for i in range ( size ) : NEW_LINE INDENT badChar [ ord ( string [ i ] ) ] = i ; NEW_LINE DEDENT return badChar NEW_LINE DEDENT def search ( txt , pat ) : NEW_LINE INDENT m = len ( pat ) NEW_LINE n = len ( txt ) NEW_LINE badChar = badCharHeuristic ( pat , m ) NEW_LINE s = 0 NEW_LINE while ( s <= n - m ) : NEW_LINE INDENT j = m - 1 NEW_LINE while j >= 0 and pat [ j ] == txt [ s + j ] : NEW_LINE INDENT j -= 1 NEW_LINE DEDENT if j < 0 : NEW_LINE INDENT print ( " Pattern β occur β at β shift β = β { } " . format ( s ) ) NEW_LINE s += ( m - badChar [ ord ( txt [ s + m ] ) ] if s + m < n else 1 ) NEW_LINE DEDENT else : NEW_LINE INDENT s += max ( 1 , j - badChar [ ord ( txt [ s + j ] ) ] ) NEW_LINE DEDENT DEDENT DEDENT def main ( ) : NEW_LINE INDENT txt = " ABAAABCD " NEW_LINE pat = " ABC " NEW_LINE search ( txt , pat ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT main ( ) NEW_LINE DEDENT |
Anagram Substring Search ( Or Search for all permutations ) | Python program to search all anagrams of a pattern in a text ; This function returns true if contents of arr1 [ ] and arr2 [ ] are same , otherwise false . ; This function search for all permutations of pat [ ] in txt [ ] ; countP [ ] : Store count of all characters of pattern countTW [ ] : Store count of current window of text ; Traverse through remaining characters of pattern ; Compare counts of current window of text with counts of pattern [ ] ; Add current character to current window ; Remove the first character of previous window ; Check for the last window in text ; Driver program to test above function | MAX = 256 NEW_LINE def compare ( arr1 , arr2 ) : NEW_LINE INDENT for i in range ( MAX ) : NEW_LINE INDENT if arr1 [ i ] != arr2 [ i ] : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT return True NEW_LINE DEDENT def search ( pat , txt ) : NEW_LINE INDENT M = len ( pat ) NEW_LINE N = len ( txt ) NEW_LINE countP = [ 0 ] * MAX NEW_LINE countTW = [ 0 ] * MAX NEW_LINE for i in range ( M ) : NEW_LINE INDENT ( countP [ ord ( pat [ i ] ) ] ) += 1 NEW_LINE ( countTW [ ord ( txt [ i ] ) ] ) += 1 NEW_LINE DEDENT for i in range ( M , N ) : NEW_LINE INDENT if compare ( countP , countTW ) : NEW_LINE INDENT print ( " Found β at β Index " , ( i - M ) ) NEW_LINE DEDENT ( countTW [ ord ( txt [ i ] ) ] ) += 1 NEW_LINE ( countTW [ ord ( txt [ i - M ] ) ] ) -= 1 NEW_LINE DEDENT if compare ( countP , countTW ) : NEW_LINE INDENT print ( " Found β at β Index " , N - M ) NEW_LINE DEDENT DEDENT txt = " BACDGABCDA " NEW_LINE pat = " ABCD " NEW_LINE search ( pat , txt ) NEW_LINE |
Manacher 's Algorithm | Python program to implement Manacher 's Algorithm ; Position count ; LPS Length Array ; centerPosition ; centerRightPosition ; currentRightPosition ; currentLeftPosition ; Uncomment it to print LPS Length array printf ( " % d β % d β " , L [ 0 ] , L [ 1 ] ) ; ; get currentLeftPosition iMirror for currentRightPosition i ; If currentRightPosition i is within centerRightPosition R ; Attempt to expand palindrome centered at currentRightPosition i Here for odd positions , we compare characters and if match then increment LPS Length by ONE If even position , we just increment LPS by ONE without any character comparison ; Track maxLPSLength ; If palindrome centered at currentRightPosition i expand beyond centerRightPosition R , adjust centerPosition C based on expanded palindrome . ; Uncomment it to print LPS Length array printf ( " % d β " , L [ i ] ) ; ; Driver program | def findLongestPalindromicString ( text ) : NEW_LINE INDENT N = len ( text ) NEW_LINE if N == 0 : NEW_LINE INDENT return NEW_LINE DEDENT N = 2 * N + 1 NEW_LINE L = [ 0 ] * N NEW_LINE L [ 0 ] = 0 NEW_LINE L [ 1 ] = 1 NEW_LINE C = 1 NEW_LINE R = 2 NEW_LINE i = 0 NEW_LINE iMirror = 0 NEW_LINE maxLPSLength = 0 NEW_LINE maxLPSCenterPosition = 0 NEW_LINE start = - 1 NEW_LINE end = - 1 NEW_LINE diff = - 1 NEW_LINE for i in xrange ( 2 , N ) : NEW_LINE INDENT iMirror = 2 * C - i NEW_LINE L [ i ] = 0 NEW_LINE diff = R - i NEW_LINE if diff > 0 : NEW_LINE INDENT L [ i ] = min ( L [ iMirror ] , diff ) NEW_LINE DEDENT try : NEW_LINE INDENT while ( ( i + L [ i ] ) < N and ( i - L [ i ] ) > 0 ) and ( ( ( i + L [ i ] + 1 ) % 2 == 0 ) or ( text [ ( i + L [ i ] + 1 ) / 2 ] == text [ ( i - L [ i ] - 1 ) / 2 ] ) ) : NEW_LINE INDENT L [ i ] += 1 NEW_LINE DEDENT DEDENT except Exception as e : NEW_LINE INDENT pass NEW_LINE DEDENT if L [ i ] > maxLPSLength : NEW_LINE INDENT maxLPSLength = L [ i ] NEW_LINE maxLPSCenterPosition = i NEW_LINE DEDENT if i + L [ i ] > R : NEW_LINE INDENT C = i NEW_LINE R = i + L [ i ] NEW_LINE DEDENT DEDENT start = ( maxLPSCenterPosition - maxLPSLength ) / 2 NEW_LINE end = start + maxLPSLength - 1 NEW_LINE print " LPS β of β string β is β " + text + " β : β " , NEW_LINE print text [ start : end + 1 ] , NEW_LINE print " NEW_LINE DEDENT " , NEW_LINE text1 = " babcbabcbaccba " NEW_LINE findLongestPalindromicString ( text1 ) NEW_LINE text2 = " abaaba " NEW_LINE findLongestPalindromicString ( text2 ) NEW_LINE text3 = " abababa " NEW_LINE findLongestPalindromicString ( text3 ) NEW_LINE text4 = " abcbabcbabcba " NEW_LINE findLongestPalindromicString ( text4 ) NEW_LINE text5 = " forgeeksskeegfor " NEW_LINE findLongestPalindromicString ( text5 ) NEW_LINE text6 = " caba " NEW_LINE findLongestPalindromicString ( text6 ) NEW_LINE text7 = " abacdfgdcaba " NEW_LINE findLongestPalindromicString ( text7 ) NEW_LINE text8 = " abacdfgdcabba " NEW_LINE findLongestPalindromicString ( text8 ) NEW_LINE text9 = " abacdedcaba " NEW_LINE findLongestPalindromicString ( text9 ) NEW_LINE |
Sudoku | Backtracking | N is the size of the 2D matrix N * N ; A utility function to print grid ; Checks whether it will be legal to assign num to the given row , col ; Check if we find the same num in the similar row , we return false ; Check if we find the same num in the similar column , we return false ; Check if we find the same num in the particular 3 * 3 matrix , we return false ; Takes a partially filled - in grid and attempts to assign values to all unassigned locations in such a way to meet the requirements for Sudoku solution ( non - duplication across rows , columns , and boxes ) ; Check if we have reached the 8 th row and 9 th column ( 0 indexed matrix ) , we are returning true to avoid further backtracking ; Check if column value becomes 9 , we move to next row and column start from 0 ; Check if the current position of the grid already contains value > 0 , we iterate for next column ; Check if it is safe to place the num ( 1 - 9 ) in the given row , col -> we move to next column ; Assigning the num in the current ( row , col ) position of the grid and assuming our assined num in the position is correct ; Checking for next possibility with next column ; Removing the assigned num , since our assumption was wrong , and we go for next assumption with diff num value ; Driver Code 0 means unassigned cells | N = 9 NEW_LINE def printing ( arr ) : NEW_LINE INDENT for i in range ( N ) : NEW_LINE INDENT for j in range ( N ) : NEW_LINE INDENT print ( arr [ i ] [ j ] , end = " β " ) NEW_LINE DEDENT print ( ) NEW_LINE DEDENT DEDENT def isSafe ( grid , row , col , num ) : NEW_LINE INDENT for x in range ( 9 ) : NEW_LINE INDENT if grid [ row ] [ x ] == num : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT for x in range ( 9 ) : NEW_LINE INDENT if grid [ x ] [ col ] == num : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT startRow = row - row % 3 NEW_LINE startCol = col - col % 3 NEW_LINE for i in range ( 3 ) : NEW_LINE INDENT for j in range ( 3 ) : NEW_LINE INDENT if grid [ i + startRow ] [ j + startCol ] == num : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT DEDENT return True NEW_LINE DEDENT def solveSuduko ( grid , row , col ) : NEW_LINE INDENT if ( row == N - 1 and col == N ) : NEW_LINE INDENT return True NEW_LINE DEDENT if col == N : NEW_LINE INDENT row += 1 NEW_LINE col = 0 NEW_LINE DEDENT if grid [ row ] [ col ] > 0 : NEW_LINE INDENT return solveSuduko ( grid , row , col + 1 ) NEW_LINE DEDENT for num in range ( 1 , N + 1 , 1 ) : NEW_LINE INDENT if isSafe ( grid , row , col , num ) : NEW_LINE INDENT grid [ row ] [ col ] = num NEW_LINE if solveSuduko ( grid , row , col + 1 ) : NEW_LINE INDENT return True NEW_LINE DEDENT DEDENT grid [ row ] [ col ] = 0 NEW_LINE DEDENT return False NEW_LINE DEDENT grid = [ [ 3 , 0 , 6 , 5 , 0 , 8 , 4 , 0 , 0 ] , [ 5 , 2 , 0 , 0 , 0 , 0 , 0 , 0 , 0 ] , [ 0 , 8 , 7 , 0 , 0 , 0 , 0 , 3 , 1 ] , [ 0 , 0 , 3 , 0 , 1 , 0 , 0 , 8 , 0 ] , [ 9 , 0 , 0 , 8 , 6 , 3 , 0 , 0 , 5 ] , [ 0 , 5 , 0 , 0 , 9 , 0 , 6 , 0 , 0 ] , [ 1 , 3 , 0 , 0 , 0 , 0 , 2 , 5 , 0 ] , [ 0 , 0 , 0 , 0 , 0 , 0 , 0 , 7 , 4 ] , [ 0 , 0 , 5 , 2 , 0 , 6 , 3 , 0 , 0 ] ] NEW_LINE if ( solveSuduko ( grid , 0 , 0 ) ) : NEW_LINE INDENT printing ( grid ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " no β solution β exists β " ) NEW_LINE DEDENT |
Median of two sorted arrays of same size | This function returns median of ar1 [ ] and ar2 [ ] . Assumptions in this function : Both ar1 [ ] and ar2 [ ] are sorted arrays Both have n elements ; Since there are 2 n elements , median will be average of elements at index n - 1 and n in the array obtained after merging ar1 and ar2 ; Below is to handle case where all elements of ar1 [ ] are smaller than smallest ( or first ) element of ar2 [ ] ; Below is to handle case where all elements of ar2 [ ] are smaller than smallest ( or first ) element of ar1 [ ] ; equals sign because if two arrays have some common elements ; Store the prev median ; Store the prev median ; Driver code to test above function | def getMedian ( ar1 , ar2 , n ) : NEW_LINE INDENT i = 0 NEW_LINE j = 0 NEW_LINE m1 = - 1 NEW_LINE m2 = - 1 NEW_LINE count = 0 NEW_LINE while count < n + 1 : NEW_LINE INDENT count += 1 NEW_LINE if i == n : NEW_LINE INDENT m1 = m2 NEW_LINE m2 = ar2 [ 0 ] NEW_LINE break NEW_LINE DEDENT elif j == n : NEW_LINE INDENT m1 = m2 NEW_LINE m2 = ar1 [ 0 ] NEW_LINE break NEW_LINE DEDENT if ar1 [ i ] <= ar2 [ j ] : NEW_LINE INDENT m1 = m2 NEW_LINE m2 = ar1 [ i ] NEW_LINE i += 1 NEW_LINE DEDENT else : NEW_LINE INDENT m1 = m2 NEW_LINE m2 = ar2 [ j ] NEW_LINE j += 1 NEW_LINE DEDENT DEDENT return ( m1 + m2 ) / 2 NEW_LINE DEDENT ar1 = [ 1 , 12 , 15 , 26 , 38 ] NEW_LINE ar2 = [ 2 , 13 , 17 , 30 , 45 ] NEW_LINE n1 = len ( ar1 ) NEW_LINE n2 = len ( ar2 ) NEW_LINE if n1 == n2 : NEW_LINE INDENT print ( " Median β is β " , getMedian ( ar1 , ar2 , n1 ) ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " Doesn ' t β work β for β arrays β of β unequal β size " ) NEW_LINE DEDENT |
Median of two sorted arrays of same size | while loop to swap all smaller numbers to arr1 ; Driver program | def getMedian ( ar1 , ar2 , n ) : NEW_LINE INDENT i , j = n - 1 , 0 NEW_LINE while ( ar1 [ i ] > ar2 [ j ] and i > - 1 and j < n ) : NEW_LINE INDENT ar1 [ i ] , ar2 [ j ] = ar2 [ j ] , ar1 [ i ] NEW_LINE i -= 1 NEW_LINE j += 1 NEW_LINE DEDENT ar1 . sort ( ) NEW_LINE ar2 . sort ( ) NEW_LINE return ( ar1 [ - 1 ] + ar2 [ 0 ] ) >> 1 NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT ar1 = [ 1 , 12 , 15 , 26 , 38 ] NEW_LINE ar2 = [ 2 , 13 , 17 , 30 , 45 ] NEW_LINE n1 , n2 = len ( ar1 ) , len ( ar2 ) NEW_LINE if ( n1 == n2 ) : NEW_LINE INDENT print ( ' Median β is ' , getMedian ( ar1 , ar2 , n1 ) ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " Doesn ' t β work β for β arrays β of β unequal β size " ) NEW_LINE DEDENT DEDENT |
Closest Pair of Points using Divide and Conquer algorithm | A divide and conquer program in Python3 to find the smallest distance from a given set of points . ; A class to represent a Point in 2D plane ; A utility function to find the distance between two points ; A Brute Force method to return the smallest distance between two points in P [ ] of size n ; A utility function to find the distance beween the closest points of strip of given size . All points in strip [ ] are sorted accordint to y coordinate . They all have an upper bound on minimum distance as d . Note that this method seems to be a O ( n ^ 2 ) method , but it 's a O(n) method as the inner loop runs at most 6 times ; Initialize the minimum distance as d ; Pick all points one by one and try the next points till the difference between y coordinates is smaller than d . This is a proven fact that this loop runs at most 6 times ; A recursive function to find the smallest distance . The array P contains all points sorted according to x coordinate ; If there are 2 or 3 points , then use brute force ; Find the middle point ; keep a copy of left and right branch ; Consider the vertical line passing through the middle point calculate the smallest distance dl on left of middle point and dr on right side ; Find the smaller of two distances ; Build an array strip [ ] that contains points close ( closer than d ) to the line passing through the middle point ; < -- REQUIRED ; Find the self . closest points in strip . Return the minimum of d and self . closest distance is strip [ ] ; The main function that finds the smallest distance . This method mainly uses closestUtil ( ) ; Use recursive function closestUtil ( ) to find the smallest distance ; Driver code | import math NEW_LINE import copy NEW_LINE 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 def dist ( p1 , p2 ) : NEW_LINE INDENT return math . sqrt ( ( p1 . x - p2 . x ) * ( p1 . x - p2 . x ) + ( p1 . y - p2 . y ) * ( p1 . y - p2 . y ) ) NEW_LINE DEDENT def bruteForce ( P , n ) : NEW_LINE INDENT min_val = float ( ' inf ' ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT for j in range ( i + 1 , n ) : NEW_LINE INDENT if dist ( P [ i ] , P [ j ] ) < min_val : NEW_LINE INDENT min_val = dist ( P [ i ] , P [ j ] ) NEW_LINE DEDENT DEDENT DEDENT return min_val NEW_LINE DEDENT def stripClosest ( strip , size , d ) : NEW_LINE INDENT min_val = d NEW_LINE for i in range ( size ) : NEW_LINE INDENT j = i + 1 NEW_LINE while j < size and ( strip [ j ] . y - strip [ i ] . y ) < min_val : NEW_LINE INDENT min_val = dist ( strip [ i ] , strip [ j ] ) NEW_LINE j += 1 NEW_LINE DEDENT DEDENT return min_val NEW_LINE DEDENT def closestUtil ( P , Q , n ) : NEW_LINE INDENT if n <= 3 : NEW_LINE INDENT return bruteForce ( P , n ) NEW_LINE DEDENT mid = n // 2 NEW_LINE midPoint = P [ mid ] NEW_LINE Pl = P [ : mid ] NEW_LINE Pr = P [ mid : ] NEW_LINE dl = closestUtil ( Pl , Q , mid ) NEW_LINE dr = closestUtil ( Pr , Q , n - mid ) NEW_LINE d = min ( dl , dr ) NEW_LINE stripP = [ ] NEW_LINE stripQ = [ ] NEW_LINE lr = Pl + Pr NEW_LINE for i in range ( n ) : NEW_LINE INDENT if abs ( lr [ i ] . x - midPoint . x ) < d : NEW_LINE INDENT stripP . append ( lr [ i ] ) NEW_LINE DEDENT if abs ( Q [ i ] . x - midPoint . x ) < d : NEW_LINE INDENT stripQ . append ( Q [ i ] ) NEW_LINE DEDENT DEDENT stripP . sort ( key = lambda point : point . y ) NEW_LINE min_a = min ( d , stripClosest ( stripP , len ( stripP ) , d ) ) NEW_LINE min_b = min ( d , stripClosest ( stripQ , len ( stripQ ) , d ) ) NEW_LINE return min ( min_a , min_b ) NEW_LINE DEDENT def closest ( P , n ) : NEW_LINE INDENT P . sort ( key = lambda point : point . x ) NEW_LINE Q = copy . deepcopy ( P ) NEW_LINE Q . sort ( key = lambda point : point . y ) NEW_LINE return closestUtil ( P , Q , n ) NEW_LINE DEDENT P = [ Point ( 2 , 3 ) , Point ( 12 , 30 ) , Point ( 40 , 50 ) , Point ( 5 , 1 ) , Point ( 12 , 10 ) , Point ( 3 , 4 ) ] NEW_LINE n = len ( P ) NEW_LINE print ( " The β smallest β distance β is " , closest ( P , n ) ) NEW_LINE |
How to check if two given line segments intersect ? | A Python3 program to find if 2 given line segments intersect or not ; Given three colinear points p , q , r , the function checks if point q lies on line segment ' pr ' ; to find the orientation of an ordered triplet ( p , q , r ) function returns the following values : 0 : Colinear points 1 : Clockwise points 2 : Counterclockwise See https : www . geeksforgeeks . org / orientation - 3 - ordered - points / amp / for details of below formula . ; Counterclockwise orientation ; The main function that returns true if the line segment ' p1q1' and ' p2q2' intersect . ; Find the 4 orientations required for the general and special cases ; General case ; Special Cases p1 , q1 and p2 are colinear and p2 lies on segment p1q1 ; p1 , q1 and q2 are colinear and q2 lies on segment p1q1 ; p2 , q2 and p1 are colinear and p1 lies on segment p2q2 ; p2 , q2 and q1 are colinear and q1 lies on segment p2q2 ; If none of the cases ; Driver program to test above functions : | 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 def onSegment ( p , q , r ) : NEW_LINE INDENT if ( ( q . x <= max ( p . x , r . x ) ) and ( q . x >= min ( p . x , r . x ) ) and ( q . y <= max ( p . y , r . y ) ) and ( q . y >= min ( p . y , r . y ) ) ) : NEW_LINE INDENT return True NEW_LINE DEDENT return False NEW_LINE DEDENT def orientation ( p , q , r ) : NEW_LINE INDENT val = ( float ( q . y - p . y ) * ( r . x - q . x ) ) - ( float ( q . x - p . x ) * ( r . y - q . y ) ) NEW_LINE if ( val > 0 ) : NEW_LINE INDENT return 1 NEW_LINE DEDENT elif ( val < 0 ) : NEW_LINE INDENT return 2 NEW_LINE DEDENT else : NEW_LINE INDENT return 0 NEW_LINE DEDENT DEDENT def doIntersect ( p1 , q1 , p2 , q2 ) : NEW_LINE INDENT o1 = orientation ( p1 , q1 , p2 ) NEW_LINE o2 = orientation ( p1 , q1 , q2 ) NEW_LINE o3 = orientation ( p2 , q2 , p1 ) NEW_LINE o4 = orientation ( p2 , q2 , q1 ) NEW_LINE if ( ( o1 != o2 ) and ( o3 != o4 ) ) : NEW_LINE INDENT return True NEW_LINE DEDENT if ( ( o1 == 0 ) and onSegment ( p1 , p2 , q1 ) ) : NEW_LINE INDENT return True NEW_LINE DEDENT if ( ( o2 == 0 ) and onSegment ( p1 , q2 , q1 ) ) : NEW_LINE INDENT return True NEW_LINE DEDENT if ( ( o3 == 0 ) and onSegment ( p2 , p1 , q2 ) ) : NEW_LINE INDENT return True NEW_LINE DEDENT if ( ( o4 == 0 ) and onSegment ( p2 , q1 , q2 ) ) : NEW_LINE INDENT return True NEW_LINE DEDENT return False NEW_LINE DEDENT p1 = Point ( 1 , 1 ) NEW_LINE q1 = Point ( 10 , 1 ) NEW_LINE p2 = Point ( 1 , 2 ) NEW_LINE q2 = Point ( 10 , 2 ) NEW_LINE if doIntersect ( p1 , q1 , p2 , q2 ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT p1 = Point ( 10 , 0 ) NEW_LINE q1 = Point ( 0 , 10 ) NEW_LINE p2 = Point ( 0 , 0 ) NEW_LINE q2 = Point ( 10 , 10 ) NEW_LINE if doIntersect ( p1 , q1 , p2 , q2 ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT p1 = Point ( - 5 , - 5 ) NEW_LINE q1 = Point ( 0 , 0 ) NEW_LINE p2 = Point ( 1 , 1 ) NEW_LINE q2 = Point ( 10 , 10 ) NEW_LINE if doIntersect ( p1 , q1 , p2 , q2 ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT |
Check whether a given point lies inside a triangle or not | A utility function to calculate area of triangle formed by ( x1 , y1 ) , ( x2 , y2 ) and ( x3 , y3 ) ; A function to check whether point P ( x , y ) lies inside the triangle formed by A ( x1 , y1 ) , B ( x2 , y2 ) and C ( x3 , y3 ) ; Calculate area of triangle ABC ; Calculate area of triangle PBC ; Calculate area of triangle PAC ; Calculate area of triangle PAB ; Check if sum of A1 , A2 and A3 is same as A ; Let us check whether the point P ( 10 , 15 ) lies inside the triangle formed by A ( 0 , 0 ) , B ( 20 , 0 ) and C ( 10 , 30 ) | def area ( x1 , y1 , x2 , y2 , x3 , y3 ) : NEW_LINE INDENT return abs ( ( x1 * ( y2 - y3 ) + x2 * ( y3 - y1 ) + x3 * ( y1 - y2 ) ) / 2.0 ) NEW_LINE DEDENT def isInside ( x1 , y1 , x2 , y2 , x3 , y3 , x , y ) : NEW_LINE INDENT A = area ( x1 , y1 , x2 , y2 , x3 , y3 ) NEW_LINE A1 = area ( x , y , x2 , y2 , x3 , y3 ) NEW_LINE A2 = area ( x1 , y1 , x , y , x3 , y3 ) NEW_LINE A3 = area ( x1 , y1 , x2 , y2 , x , y ) NEW_LINE if ( A == A1 + A2 + A3 ) : NEW_LINE INDENT return True NEW_LINE DEDENT else : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT if ( isInside ( 0 , 0 , 20 , 0 , 10 , 30 , 10 , 15 ) ) : NEW_LINE INDENT print ( ' Inside ' ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( ' Not β Inside ' ) NEW_LINE DEDENT |
Lucky Numbers | Returns 1 if n is a lucky number otherwise returns 0 ; Function attribute will act as static variable just for readability , can be removed and used n instead ; Calculate next position of input number ; Driver Code Acts as static variable | def isLucky ( n ) : NEW_LINE INDENT next_position = n NEW_LINE if isLucky . counter > n : NEW_LINE INDENT return 1 NEW_LINE DEDENT if n % isLucky . counter == 0 : NEW_LINE INDENT return 0 NEW_LINE DEDENT next_position = next_position - next_position / isLucky . counter NEW_LINE isLucky . counter = isLucky . counter + 1 NEW_LINE return isLucky ( next_position ) NEW_LINE DEDENT isLucky . counter = 2 NEW_LINE x = 5 NEW_LINE if isLucky ( x ) : NEW_LINE INDENT print x , " is β a β Lucky β number " NEW_LINE DEDENT else : NEW_LINE INDENT print x , " is β not β a β Lucky β number " NEW_LINE DEDENT |
Write you own Power without using multiplication ( * ) and division ( / ) operators | Works only if a >= 0 and b >= 0 ; driver code | def pow ( a , b ) : NEW_LINE INDENT if ( b == 0 ) : NEW_LINE INDENT return 1 NEW_LINE DEDENT answer = a NEW_LINE increment = a NEW_LINE for i in range ( 1 , b ) : NEW_LINE INDENT for j in range ( 1 , a ) : NEW_LINE INDENT answer += increment NEW_LINE DEDENT increment = answer NEW_LINE DEDENT return answer NEW_LINE DEDENT print ( pow ( 5 , 3 ) ) NEW_LINE |
Write you own Power without using multiplication ( * ) and division ( / ) operators | A recursive function to get x * y * ; ; driver program to test above functions * | def multiply ( x , y ) : NEW_LINE INDENT if ( y ) : NEW_LINE INDENT return ( x + multiply ( x , y - 1 ) ) ; NEW_LINE DEDENT else : NEW_LINE INDENT return 0 ; NEW_LINE DEDENT DEDENT def pow ( a , b ) : NEW_LINE INDENT if ( b ) : NEW_LINE INDENT return multiply ( a , pow ( a , b - 1 ) ) ; NEW_LINE DEDENT else : NEW_LINE INDENT return 1 ; NEW_LINE DEDENT DEDENT print ( pow ( 5 , 3 ) ) ; NEW_LINE |
Count numbers that don 't contain 3 | Returns count of numbers which are in range from 1 to n and don 't contain 3 as a digit ; Base Cases ( n is not negative ) ; Calculate 10 ^ ( d - 1 ) ( 10 raise to the power d - 1 ) where d is number of digits in n . po will be 100 for n = 578 ; Find the MSD ( msd is 5 for 578 ) ; For 578 , total will be 4 * count ( 10 ^ 2 - 1 ) + 4 + ccount ( 78 ) ; For 35 total will be equal to count ( 29 ) ; Driver Program | def count ( n ) : NEW_LINE INDENT if n < 3 : NEW_LINE INDENT return n NEW_LINE DEDENT elif n >= 3 and n < 10 : NEW_LINE INDENT return n - 1 NEW_LINE DEDENT po = 1 NEW_LINE while n / po > 9 : NEW_LINE INDENT po = po * 10 NEW_LINE DEDENT msd = n / po NEW_LINE if msd != 3 : NEW_LINE INDENT return count ( msd ) * count ( po - 1 ) + count ( msd ) + count ( n % po ) NEW_LINE DEDENT else : NEW_LINE INDENT return count ( msd * po - 1 ) NEW_LINE DEDENT DEDENT n = 578 NEW_LINE print count ( n ) NEW_LINE |
Number which has the maximum number of distinct prime factors in the range M to N | Function to return the maximum number ; array to store the number of distinct primes ; true if index ' i ' is a prime ; initializing the number of factors to 0 and ; Used in Sieve ; condition works only when ' i ' is prime , hence for factors of all prime number , the prime status is changed to false ; Number is prime ; number of factor of a prime number is 1 ; incrementing factorCount all the factors of i ; and changing prime status to false ; Initialize the max and num ; Gets the maximum number ; Gets the maximum number ; Driver code ; Calling function | def maximumNumberDistinctPrimeRange ( m , n ) : NEW_LINE INDENT factorCount = [ 0 ] * ( n + 1 ) NEW_LINE prime = [ False ] * ( n + 1 ) NEW_LINE for i in range ( n + 1 ) : NEW_LINE INDENT factorCount [ i ] = 0 NEW_LINE prime [ i ] = True NEW_LINE DEDENT for i in range ( 2 , n + 1 ) : NEW_LINE INDENT if ( prime [ i ] == True ) : NEW_LINE INDENT factorCount [ i ] = 1 NEW_LINE for j in range ( i * 2 , n + 1 , i ) : NEW_LINE INDENT factorCount [ j ] += 1 NEW_LINE prime [ j ] = False NEW_LINE DEDENT DEDENT DEDENT max = factorCount [ m ] NEW_LINE num = m NEW_LINE for i in range ( m , n + 1 ) : NEW_LINE INDENT if ( factorCount [ i ] > max ) : NEW_LINE INDENT max = factorCount [ i ] NEW_LINE num = i NEW_LINE DEDENT DEDENT return num NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT m = 4 NEW_LINE n = 6 NEW_LINE print ( maximumNumberDistinctPrimeRange ( m , n ) ) NEW_LINE DEDENT |
Lexicographic rank of a string | A utility function to find factorial of n ; A utility function to count smaller characters on right of arr [ low ] ; A function to find rank of a string in all permutations of characters ; count number of chars smaller than str [ i ] fron str [ i + 1 ] to str [ len - 1 ] ; Driver program to test above function | def fact ( n ) : NEW_LINE INDENT f = 1 NEW_LINE while n >= 1 : NEW_LINE INDENT f = f * n NEW_LINE n = n - 1 NEW_LINE DEDENT return f NEW_LINE DEDENT def findSmallerInRight ( st , low , high ) : NEW_LINE INDENT countRight = 0 NEW_LINE i = low + 1 NEW_LINE while i <= high : NEW_LINE INDENT if st [ i ] < st [ low ] : NEW_LINE INDENT countRight = countRight + 1 NEW_LINE DEDENT i = i + 1 NEW_LINE DEDENT return countRight NEW_LINE DEDENT def findRank ( st ) : NEW_LINE INDENT ln = len ( st ) NEW_LINE mul = fact ( ln ) NEW_LINE rank = 1 NEW_LINE i = 0 NEW_LINE while i < ln : NEW_LINE INDENT mul = mul / ( ln - i ) NEW_LINE countRight = findSmallerInRight ( st , i , ln - 1 ) NEW_LINE rank = rank + countRight * mul NEW_LINE i = i + 1 NEW_LINE DEDENT return rank NEW_LINE DEDENT st = " string " NEW_LINE print ( findRank ( st ) ) NEW_LINE |
Lexicographic rank of a string | A O ( n ) solution for finding rank of string ; all elements of count [ ] are initialized with 0 ; A utility function to find factorial of n ; Construct a count array where value at every index contains count of smaller characters in whole string ; Removes a character ch from count [ ] array constructed by populateAndIncreaseCount ( ) ; A function to find rank of a string in all permutations of characters ; Populate the count array such that count [ i ] contains count of characters which are present in str and are smaller than i ; count number of chars smaller than str [ i ] fron str [ i + 1 ] to str [ len - 1 ] ; Reduce count of characters greater than str [ i ] ; Driver code | MAX_CHAR = 256 ; NEW_LINE count = [ 0 ] * ( MAX_CHAR + 1 ) ; NEW_LINE def fact ( n ) : NEW_LINE INDENT return 1 if ( n <= 1 ) else ( n * fact ( n - 1 ) ) ; NEW_LINE DEDENT def populateAndIncreaseCount ( str ) : NEW_LINE INDENT for i in range ( len ( str ) ) : NEW_LINE INDENT count [ ord ( str [ i ] ) ] += 1 ; NEW_LINE DEDENT for i in range ( 1 , MAX_CHAR ) : NEW_LINE INDENT count [ i ] += count [ i - 1 ] ; NEW_LINE DEDENT DEDENT def updatecount ( ch ) : NEW_LINE INDENT for i in range ( ord ( ch ) , MAX_CHAR ) : NEW_LINE INDENT count [ i ] -= 1 ; NEW_LINE DEDENT DEDENT def findRank ( str ) : NEW_LINE INDENT len1 = len ( str ) ; NEW_LINE mul = fact ( len1 ) ; NEW_LINE rank = 1 ; NEW_LINE populateAndIncreaseCount ( str ) ; NEW_LINE for i in range ( len1 ) : NEW_LINE INDENT mul = mul // ( len1 - i ) ; NEW_LINE rank += count [ ord ( str [ i ] ) - 1 ] * mul ; NEW_LINE updatecount ( str [ i ] ) ; NEW_LINE DEDENT return rank ; NEW_LINE DEDENT str = " string " ; NEW_LINE print ( findRank ( str ) ) ; NEW_LINE |
Print all permutations in sorted ( lexicographic ) order | An optimized version that uses reverse instead of sort for finding the next permutation A utility function to reverse a string str [ l . . h ] ; ; Print all permutations of str in sorted order ; Get size of string ; Sort the string in increasing order ; Print permutations one by one ; Print this permutation ; Find the rightmost character which is smaller than its next character . Let us call it ' first β char ' ; If there is no such character , all are sorted in decreasing order , means we just printed the last permutation and we are done . ; Find the ceil of ' first β char ' in right of first character . Ceil of a character is the smallest character greater than it ; Swap first and second characters ; Reverse the string on right of 'first char | def reverse ( str , l , h ) : NEW_LINE INDENT while ( l < h ) : NEW_LINE INDENT str [ l ] , str [ h ] = str [ h ] , str [ l ] NEW_LINE l += 1 NEW_LINE h -= 1 NEW_LINE DEDENT return str NEW_LINE DEDENT def findCeil ( str , c , k , n ) : NEW_LINE INDENT ans = - 1 NEW_LINE val = c NEW_LINE for i in range ( k , n + 1 ) : NEW_LINE INDENT if str [ i ] > c and str [ i ] < val : NEW_LINE INDENT val = str [ i ] NEW_LINE ans = i NEW_LINE DEDENT DEDENT return ans NEW_LINE DEDENT def sortedPermutations ( str ) : NEW_LINE INDENT size = len ( str ) NEW_LINE str = ' ' . join ( sorted ( str ) ) NEW_LINE isFinished = False NEW_LINE while ( not isFinished ) : NEW_LINE INDENT print ( str ) NEW_LINE for i in range ( size - 2 , - 1 , - 1 ) : NEW_LINE INDENT if ( str [ i ] < str [ i + 1 ] ) : NEW_LINE INDENT break NEW_LINE DEDENT DEDENT if ( i == - 1 ) : NEW_LINE INDENT isFinished = True NEW_LINE DEDENT else : NEW_LINE INDENT ceilIndex = findCeil ( str , str [ i ] , i + 1 , size - 1 ) NEW_LINE str [ i ] , str [ ceilIndex ] = str [ ceilIndex ] , str [ i ] NEW_LINE str = reverse ( str , i + 1 , size - 1 ) NEW_LINE DEDENT DEDENT DEDENT |
Efficient program to calculate e ^ x | Function to calculate value using sum of first n terms of Taylor Series ; initialize sum of series ; Driver program to test above function | def exponential ( n , x ) : NEW_LINE INDENT sum = 1.0 NEW_LINE for i in range ( n , 0 , - 1 ) : NEW_LINE INDENT sum = 1 + x * sum / i NEW_LINE DEDENT print ( " e ^ x β = " , sum ) NEW_LINE DEDENT n = 10 NEW_LINE x = 1.0 NEW_LINE exponential ( n , x ) NEW_LINE |
Random number generator in arbitrary probability distribution fashion | Python3 program to generate random numbers according to given frequency distribution ; Utility function to find ceiling of r in arr [ l . . h ] ; Same as mid = ( l + h ) / 2 ; The main function that returns a random number from arr [ ] according to distribution array defined by freq [ ] . n is size of arrays . ; Create and fill prefix array ; prefix [ n - 1 ] is sum of all frequencies . Generate a random number with value from 1 to this sum ; Find index of ceiling of r in prefix arrat ; Driver code ; Let us generate 10 random numbers accroding to given distribution | import random NEW_LINE def findCeil ( arr , r , l , h ) : NEW_LINE INDENT while ( l < h ) : NEW_LINE INDENT mid = l + ( ( h - l ) >> 1 ) ; NEW_LINE if r > arr [ mid ] : NEW_LINE INDENT l = mid + 1 NEW_LINE DEDENT else : NEW_LINE INDENT h = mid NEW_LINE DEDENT DEDENT if arr [ l ] >= r : NEW_LINE INDENT return l NEW_LINE DEDENT else : NEW_LINE INDENT return - 1 NEW_LINE DEDENT DEDENT def myRand ( arr , freq , n ) : NEW_LINE INDENT prefix = [ 0 ] * n NEW_LINE prefix [ 0 ] = freq [ 0 ] NEW_LINE for i in range ( n ) : NEW_LINE INDENT prefix [ i ] = prefix [ i - 1 ] + freq [ i ] NEW_LINE DEDENT r = random . randint ( 0 , prefix [ n - 1 ] ) + 1 NEW_LINE indexc = findCeil ( prefix , r , 0 , n - 1 ) NEW_LINE return arr [ indexc ] NEW_LINE DEDENT arr = [ 1 , 2 , 3 , 4 ] NEW_LINE freq = [ 10 , 5 , 20 , 100 ] NEW_LINE n = len ( arr ) NEW_LINE for i in range ( 5 ) : NEW_LINE INDENT print ( myRand ( arr , freq , n ) ) NEW_LINE DEDENT |
How to check if a given number is Fibonacci number ? | python program to check if x is a perfect square ; A utility function that returns true if x is perfect square ; Returns true if n is a Fibinacci Number , else false ; n is Fibinacci if one of 5 * n * n + 4 or 5 * n * n - 4 or both is a perferct square ; A utility function to test above functions | import math NEW_LINE def isPerfectSquare ( x ) : NEW_LINE INDENT s = int ( math . sqrt ( x ) ) NEW_LINE return s * s == x NEW_LINE DEDENT def isFibonacci ( n ) : NEW_LINE INDENT return isPerfectSquare ( 5 * n * n + 4 ) or isPerfectSquare ( 5 * n * n - 4 ) NEW_LINE DEDENT for i in range ( 1 , 11 ) : NEW_LINE INDENT if ( isFibonacci ( i ) == True ) : NEW_LINE INDENT print i , " is β a β Fibonacci β Number " NEW_LINE DEDENT else : NEW_LINE INDENT print i , " is β a β not β Fibonacci β Number β " NEW_LINE DEDENT DEDENT |
Count trailing zeroes in factorial of a number | Function to return trailing 0 s in factorial of n ; Initialize result ; Keep dividing n by 5 & update Count ; Driver program | def findTrailingZeros ( n ) : NEW_LINE INDENT count = 0 NEW_LINE while ( n >= 5 ) : NEW_LINE INDENT n //= 5 NEW_LINE count += n NEW_LINE DEDENT return count NEW_LINE DEDENT n = 100 NEW_LINE print ( " Count β of β trailing β 0s β " + " in β 100 ! β is " , findTrailingZeros ( n ) ) NEW_LINE |
Program for nth Catalan Number | A recursive function to find nth catalan number ; Base Case ; Catalan ( n ) is the sum of catalan ( i ) * catalan ( n - i - 1 ) ; Driver Code | def catalan ( n ) : NEW_LINE INDENT if n <= 1 : NEW_LINE INDENT return 1 NEW_LINE DEDENT res = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT res += catalan ( i ) * catalan ( n - i - 1 ) NEW_LINE DEDENT return res NEW_LINE DEDENT for i in range ( 10 ) : NEW_LINE INDENT print catalan ( i ) , NEW_LINE DEDENT |
Program for nth Catalan Number | A dynamic programming based function to find nth Catalan number ; Table to store results of subproblems ; Initialize first two values in table ; Fill entries in catalan [ ] using recursive formula ; Return last entry ; Driver code | def catalan ( n ) : NEW_LINE INDENT if ( n == 0 or n == 1 ) : NEW_LINE INDENT return 1 NEW_LINE DEDENT catalan = [ 0 ] * ( n + 1 ) NEW_LINE catalan [ 0 ] = 1 NEW_LINE catalan [ 1 ] = 1 NEW_LINE for i in range ( 2 , n + 1 ) : NEW_LINE INDENT for j in range ( i ) : NEW_LINE INDENT catalan [ i ] += catalan [ j ] * catalan [ i - j - 1 ] NEW_LINE DEDENT DEDENT return catalan [ n ] NEW_LINE DEDENT for i in range ( 10 ) : NEW_LINE INDENT print ( catalan ( i ) , end = " β " ) NEW_LINE DEDENT |
Program for nth Catalan Number | Returns value of Binomial Coefficient C ( n , k ) ; since C ( n , k ) = C ( n , n - k ) ; Calculate value of [ n * ( n - 1 ) * -- - * ( n - k + 1 ) ] / [ k * ( k - 1 ) * -- -- * 1 ] ; A Binomial coefficient based function to find nth catalan number in O ( n ) time ; Calculate value of 2 nCn ; return 2 nCn / ( n + 1 ) ; Driver Code | def binomialCoefficient ( 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 = res * ( n - i ) NEW_LINE res = res / ( i + 1 ) NEW_LINE DEDENT return res NEW_LINE DEDENT def catalan ( n ) : NEW_LINE INDENT c = binomialCoefficient ( 2 * n , n ) NEW_LINE return c / ( n + 1 ) NEW_LINE DEDENT for i in range ( 10 ) : NEW_LINE INDENT print ( catalan ( i ) , end = " β " ) NEW_LINE DEDENT |
Program for nth Catalan Number | Function to print the number ; For the first number C ( 0 ) ; Iterate till N ; Calculate the number and print it ; Driver code ; Function call | def catalan ( n ) : NEW_LINE INDENT cat_ = 1 NEW_LINE print ( cat_ , " β " , end = ' ' ) NEW_LINE for i in range ( 1 , n ) : NEW_LINE INDENT cat_ *= ( 4 * i - 2 ) ; NEW_LINE cat_ //= ( i + 1 ) ; NEW_LINE print ( cat_ , " β " , end = ' ' ) NEW_LINE DEDENT DEDENT n = 5 NEW_LINE catalan ( n ) NEW_LINE |
Write a function that generates one of 3 numbers according to given probabilities | ; This function generates ' x ' with probability px / 100 , ' y ' with probability py / 100 and ' z ' with probability pz / 100 : Assumption : px + py + pz = 100 where px , py and pz lie between 0 to 100 ; Generate a number from 1 to 100 ; r is smaller than px with probability px / 100 ; r is greater than px and smaller than or equal to px + py with probability py / 100 ; r is greater than px + py and smaller than or equal to 100 with probability pz / 100 | import random NEW_LINE def random ( x , y , z , px , py , pz ) : NEW_LINE INDENT r = random . randint ( 1 , 100 ) NEW_LINE if ( r <= px ) : NEW_LINE INDENT return x NEW_LINE DEDENT if ( r <= ( px + py ) ) : NEW_LINE INDENT return y NEW_LINE DEDENT else : NEW_LINE INDENT return z NEW_LINE DEDENT DEDENT |
Find Excel column name from a given column number | Python program to find Excel column name from a given column number ; Function to print Excel column name for a given column number ; To store current index in str which is result ; Find remainder ; if remainder is 0 , then a ' Z ' must be there in output ; If remainder is non - zero ; Reverse the string and print result ; Driver program to test the above Function | MAX = 50 NEW_LINE def printString ( n ) : NEW_LINE INDENT string = [ " \0" ] * MAX NEW_LINE i = 0 NEW_LINE while n > 0 : NEW_LINE INDENT rem = n % 26 NEW_LINE if rem == 0 : NEW_LINE INDENT string [ i ] = ' Z ' NEW_LINE i += 1 NEW_LINE n = ( n / 26 ) - 1 NEW_LINE DEDENT else : NEW_LINE INDENT string [ i ] = chr ( ( rem - 1 ) + ord ( ' A ' ) ) NEW_LINE i += 1 NEW_LINE n = n / 26 NEW_LINE DEDENT DEDENT string [ i ] = ' \0' NEW_LINE string = string [ : : - 1 ] NEW_LINE print " " . join ( string ) NEW_LINE DEDENT printString ( 26 ) NEW_LINE printString ( 51 ) NEW_LINE printString ( 52 ) NEW_LINE printString ( 80 ) NEW_LINE printString ( 676 ) NEW_LINE printString ( 702 ) NEW_LINE printString ( 705 ) NEW_LINE |
Find Excel column name from a given column number | ; Step 1 : Converting to number assuming 0 in number system ; Step 2 : Getting rid of 0 , as 0 is not part of number system ; Driver code | def printString ( n ) : NEW_LINE INDENT arr = [ 0 ] * 10000 NEW_LINE i = 0 NEW_LINE while ( n > 0 ) : NEW_LINE INDENT arr [ i ] = n % 26 NEW_LINE n = int ( n // 26 ) NEW_LINE i += 1 NEW_LINE DEDENT for j in range ( 0 , i - 1 ) : NEW_LINE INDENT if ( arr [ j ] <= 0 ) : NEW_LINE INDENT arr [ j ] += 26 NEW_LINE arr [ j + 1 ] = arr [ j + 1 ] - 1 NEW_LINE DEDENT DEDENT for j in range ( i , - 1 , - 1 ) : NEW_LINE INDENT if ( arr [ j ] > 0 ) : NEW_LINE INDENT print ( chr ( ord ( ' A ' ) + ( arr [ j ] - 1 ) ) , end = " " ) ; NEW_LINE DEDENT DEDENT print ( ) ; NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT printString ( 26 ) ; NEW_LINE printString ( 51 ) ; NEW_LINE printString ( 52 ) ; NEW_LINE printString ( 80 ) ; NEW_LINE printString ( 676 ) ; NEW_LINE printString ( 702 ) ; NEW_LINE printString ( 705 ) ; NEW_LINE DEDENT |
Calculate the angle between hour hand and minute hand | Function to Calculate angle b / w hour hand and minute hand ; validate the input ; Calculate the angles moved by hour and minute hands with reference to 12 : 00 ; Find the difference between two angles ; Return the smaller angle of two possible angles ; Driver Code | def calcAngle ( h , m ) : NEW_LINE INDENT if ( h < 0 or m < 0 or h > 12 or m > 60 ) : NEW_LINE INDENT print ( ' Wrong β input ' ) NEW_LINE DEDENT if ( h == 12 ) : NEW_LINE INDENT h = 0 NEW_LINE DEDENT if ( m == 60 ) : NEW_LINE INDENT m = 0 NEW_LINE h += 1 ; NEW_LINE if ( h > 12 ) : NEW_LINE INDENT h = h - 12 ; NEW_LINE DEDENT DEDENT hour_angle = 0.5 * ( h * 60 + m ) NEW_LINE minute_angle = 6 * m NEW_LINE angle = abs ( hour_angle - minute_angle ) NEW_LINE angle = min ( 360 - angle , angle ) NEW_LINE return angle NEW_LINE DEDENT h = 9 NEW_LINE m = 60 NEW_LINE print ( ' Angle β ' , calcAngle ( h , m ) ) NEW_LINE |
How to check if an instance of 8 puzzle is solvable ? | A utility function to count inversions in given array ' arr [ ] ' ; Value 0 is used for empty space ; This function returns true if given 8 puzzle is solvable . ; Count inversions in given 8 puzzle ; return true if inversion count is even . ; Driver code | def getInvCount ( arr ) : NEW_LINE INDENT inv_count = 0 NEW_LINE for i in range ( 0 , 2 ) : NEW_LINE INDENT for j in range ( i + 1 , 3 ) : NEW_LINE INDENT if ( arr [ j ] [ i ] > 0 and arr [ j ] [ i ] > arr [ i ] [ j ] ) : NEW_LINE INDENT inv_count += 1 NEW_LINE DEDENT DEDENT DEDENT return inv_count NEW_LINE DEDENT def isSolvable ( puzzle ) : NEW_LINE INDENT invCount = getInvCount ( puzzle ) NEW_LINE return ( invCount % 2 == 0 ) NEW_LINE DEDENT puzzle = [ [ 1 , 8 , 2 ] , [ 0 , 4 , 3 ] , [ 7 , 6 , 5 ] ] NEW_LINE if ( isSolvable ( puzzle ) ) : NEW_LINE INDENT print ( " Solvable " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " Not β Solvable " ) NEW_LINE DEDENT |
Birthday Paradox | Python3 code to approximate number of people in Birthday Paradox problem ; Returns approximate number of people for a given probability ; Driver Code | import math NEW_LINE def find ( p ) : NEW_LINE INDENT return math . ceil ( math . sqrt ( 2 * 365 * math . log ( 1 / ( 1 - p ) ) ) ) ; NEW_LINE DEDENT print ( find ( 0.70 ) ) NEW_LINE |
Count Distinct Non | This function counts number of pairs ( x , y ) that satisfy the inequality x * x + y * y < n . ; Driver program to test above function | def countSolutions ( n ) : NEW_LINE INDENT res = 0 NEW_LINE x = 0 NEW_LINE while ( x * x < n ) : NEW_LINE INDENT y = 0 NEW_LINE while ( x * x + y * y < n ) : NEW_LINE INDENT res = res + 1 NEW_LINE y = y + 1 NEW_LINE DEDENT x = x + 1 NEW_LINE DEDENT return res NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT print ( " Total β Number β of β distinct β Non - Negative β pairs β is β " , countSolutions ( 6 ) ) NEW_LINE DEDENT |
Count Distinct Non | This function counts number of pairs ( x , y ) that satisfy the inequality x * x + y * y < n . ; Find the count of different y values for x = 0. ; One by one increase value of x , and find yCount for current x . If yCount becomes 0 , then we have reached maximum possible value of x . ; Add yCount ( count of different possible values of y for current x ) to result ; Increment x ; Update yCount for current x . Keep reducing yCount while the inequality is not satisfied . ; Driver program to test above function | def countSolutions ( n ) : NEW_LINE INDENT x = 0 NEW_LINE res = 0 NEW_LINE yCount = 0 NEW_LINE while ( yCount * yCount < n ) : NEW_LINE INDENT yCount = yCount + 1 NEW_LINE DEDENT while ( yCount != 0 ) : NEW_LINE INDENT res = res + yCount NEW_LINE x = x + 1 NEW_LINE while ( yCount != 0 and ( x * x + ( yCount - 1 ) * ( yCount - 1 ) >= n ) ) : NEW_LINE INDENT yCount = yCount - 1 NEW_LINE DEDENT DEDENT return res NEW_LINE DEDENT print ( " Total β Number β of β distinct β " , , countSolutions ( 6 ) ) |
Program for Method Of False Position | Python3 implementation of Bisection Method for solving equations ; An example function whose solution is determined using Bisection Method . The function is x ^ 3 - x ^ 2 + 2 ; Prints root of func ( x ) in interval [ a , b ] ; Initialize result ; Find the point that touches x axis ; Check if the above found point is root ; Decide the side to repeat the steps ; Initial values assumed | MAX_ITER = 1000000 NEW_LINE def func ( x ) : NEW_LINE INDENT return ( x * x * x - x * x + 2 ) NEW_LINE DEDENT def regulaFalsi ( a , b ) : NEW_LINE INDENT if func ( a ) * func ( b ) >= 0 : NEW_LINE INDENT print ( " You β have β not β assumed β right β a β and β b " ) NEW_LINE return - 1 NEW_LINE DEDENT c = a NEW_LINE for i in range ( MAX_ITER ) : NEW_LINE INDENT c = ( a * func ( b ) - b * func ( a ) ) / ( func ( b ) - func ( a ) ) NEW_LINE if func ( c ) == 0 : NEW_LINE INDENT break NEW_LINE DEDENT elif func ( c ) * func ( a ) < 0 : NEW_LINE INDENT b = c NEW_LINE DEDENT else : NEW_LINE INDENT a = c NEW_LINE DEDENT DEDENT print ( " The β value β of β root β is β : β " , ' % .4f ' % c ) NEW_LINE DEDENT a = - 200 NEW_LINE b = 300 NEW_LINE regulaFalsi ( a , b ) NEW_LINE |
Program for Newton Raphson Method | An example function whose solution is determined using Bisection Method . The function is x ^ 3 - x ^ 2 + 2 ; Derivative of the above function which is 3 * x ^ x - 2 * x ; Function to find the root ; x ( i + 1 ) = x ( i ) - f ( x ) / f '(x) ; Initial values assumed | def func ( x ) : NEW_LINE INDENT return x * x * x - x * x + 2 NEW_LINE DEDENT def derivFunc ( x ) : NEW_LINE INDENT return 3 * x * x - 2 * x NEW_LINE DEDENT def newtonRaphson ( x ) : NEW_LINE INDENT h = func ( x ) / derivFunc ( x ) NEW_LINE while abs ( h ) >= 0.0001 : NEW_LINE INDENT h = func ( x ) / derivFunc ( x ) NEW_LINE x = x - h NEW_LINE DEDENT print ( " The β value β of β the β root β is β : β " , " % .4f " % x ) NEW_LINE DEDENT x0 = - 20 NEW_LINE newtonRaphson ( x0 ) NEW_LINE |
Find the element that appears once | Method to find the element that occur only once ; one & arr [ i ] " gives the bits that are there in both 'ones' and new element from arr[]. We add these bits to 'twos' using bitwise OR ; one & arr [ i ] " gives the bits that are there in both 'ones' and new element from arr[]. We add these bits to 'twos' using bitwise OR ; The common bits are those bits which appear third time . So these bits should not be there in both ' ones ' and ' twos ' . common_bit_mask contains all these bits as 0 , so that the bits can be removed from ' ones ' and 'twos ; Remove common bits ( the bits that appear third time ) from 'ones ; Remove common bits ( the bits that appear third time ) from 'twos ; driver code | def getSingle ( arr , n ) : NEW_LINE INDENT ones = 0 NEW_LINE twos = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT twos = twos | ( ones & arr [ i ] ) NEW_LINE ones = ones ^ arr [ i ] NEW_LINE common_bit_mask = ~ ( ones & twos ) NEW_LINE ones &= common_bit_mask NEW_LINE twos &= common_bit_mask NEW_LINE DEDENT return ones NEW_LINE DEDENT arr = [ 3 , 3 , 2 , 3 ] NEW_LINE n = len ( arr ) NEW_LINE print ( " The β element β with β single β occurrence β is β " , getSingle ( arr , n ) ) NEW_LINE |
Find the element that appears once | Python3 code to find the element that occur only once ; Initialize result ; Iterate through every bit ; Find sum of set bits at ith position in all array elements ; The bits with sum not multiple of 3 , are the bits of element with single occurrence . ; Driver program | INT_SIZE = 32 NEW_LINE def getSingle ( arr , n ) : NEW_LINE INDENT result = 0 NEW_LINE for i in range ( 0 , INT_SIZE ) : NEW_LINE INDENT sm = 0 NEW_LINE x = ( 1 << i ) NEW_LINE for j in range ( 0 , n ) : NEW_LINE INDENT if ( arr [ j ] & x ) : NEW_LINE INDENT sm = sm + 1 NEW_LINE DEDENT DEDENT if ( ( sm % 3 ) != 0 ) : NEW_LINE INDENT result = result | x NEW_LINE DEDENT DEDENT return result NEW_LINE DEDENT arr = [ 12 , 1 , 12 , 3 , 12 , 1 , 1 , 2 , 3 , 2 , 2 , 3 , 7 ] NEW_LINE n = len ( arr ) NEW_LINE print ( " The β element β with β single β occurrence β is β " , getSingle ( arr , n ) ) NEW_LINE |
Detect if two integers have opposite signs | Function to detect signs ; Driver Code | def oppositeSigns ( x , y ) : NEW_LINE INDENT return ( ( x ^ y ) < 0 ) ; NEW_LINE DEDENT x = 100 NEW_LINE y = 1 NEW_LINE if ( oppositeSigns ( x , y ) == True ) : NEW_LINE INDENT print " Signs β are β opposite " NEW_LINE DEDENT else : NEW_LINE INDENT print " Signs β are β not β opposite " NEW_LINE DEDENT |
Count total set bits in all numbers from 1 to n | Returns count of set bits present in all numbers from 1 to n ; initialize the result ; A utility function to count set bits in a number x ; Driver program | def countSetBits ( n ) : NEW_LINE INDENT bitCount = 0 NEW_LINE for i in range ( 1 , n + 1 ) : NEW_LINE INDENT bitCount += countSetBitsUtil ( i ) NEW_LINE DEDENT return bitCount NEW_LINE DEDENT def countSetBitsUtil ( x ) : NEW_LINE INDENT if ( x <= 0 ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT return ( 0 if int ( x % 2 ) == 0 else 1 ) + countSetBitsUtil ( int ( x / 2 ) ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT n = 4 NEW_LINE print ( " Total β set β bit β count β is " , countSetBits ( n ) ) NEW_LINE DEDENT |
Count total set bits in all numbers from 1 to n | Function which counts set bits from 0 to n ; ans store sum of set bits from 0 to n ; while n greater than equal to 2 ^ i ; This k will get flipped after 2 ^ i iterations ; change is iterator from 2 ^ i to 1 ; This will loop from 0 to n for every bit position ; When change = 1 flip the bit ; again set change to 2 ^ i ; increment the position ; Driver code | def countSetBits ( n ) : NEW_LINE INDENT i = 0 NEW_LINE ans = 0 NEW_LINE while ( ( 1 << i ) <= n ) : NEW_LINE INDENT k = 0 NEW_LINE change = 1 << i NEW_LINE for j in range ( 0 , n + 1 ) : NEW_LINE INDENT ans += k NEW_LINE if change == 1 : NEW_LINE INDENT k = not k NEW_LINE change = 1 << i NEW_LINE DEDENT else : NEW_LINE INDENT change -= 1 NEW_LINE DEDENT DEDENT i += 1 NEW_LINE DEDENT return ans NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT n = 17 NEW_LINE print ( countSetBits ( n ) ) NEW_LINE DEDENT |
Count total set bits in all numbers from 1 to n | Returns position of leftmost set bit . The rightmost position is considered as 0 ; Given the position of previous leftmost set bit in n ( or an upper bound onleftmost position ) returns the new position of leftmost set bit in n ; The main recursive function used by countSetBits ( ) def _countSetBits ( n , m ) Returns count of set bits present in all numbers from 1 to n ; Get the position of leftmost set bit in n . This will be used as an upper bound for next set bit function ; Use the position ; Base Case : if n is 0 , then set bit count is 0 ; get position of next leftmost set bit ; If n is of the form 2 ^ x - 1 , i . e . , if n is like 1 , 3 , 7 , 15 , 31 , . . etc , then we are done . Since positions are considered starting from 0 , 1 is added to m ; update n for next recursive call ; Driver code | def getLeftmostBit ( n ) : NEW_LINE INDENT m = 0 NEW_LINE while ( n > 1 ) : NEW_LINE INDENT n = n >> 1 NEW_LINE m += 1 NEW_LINE DEDENT return m NEW_LINE DEDENT def getNextLeftmostBit ( n , m ) : NEW_LINE INDENT temp = 1 << m NEW_LINE while ( n < temp ) : NEW_LINE INDENT temp = temp >> 1 NEW_LINE m -= 1 NEW_LINE DEDENT return m NEW_LINE DEDENT def countSetBits ( n ) : NEW_LINE INDENT m = getLeftmostBit ( n ) NEW_LINE return _countSetBits ( n , m ) NEW_LINE DEDENT def _countSetBits ( n , m ) : NEW_LINE INDENT if ( n == 0 ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT m = getNextLeftmostBit ( n , m ) NEW_LINE if ( n == ( 1 << ( m + 1 ) ) - 1 ) : NEW_LINE INDENT return ( ( m + 1 ) * ( 1 << m ) ) NEW_LINE DEDENT n = n - ( 1 << m ) NEW_LINE return ( n + 1 ) + countSetBits ( n ) + m * ( 1 << ( m - 1 ) ) NEW_LINE DEDENT n = 17 NEW_LINE print ( " Total β set β bit β count β is " , countSetBits ( n ) ) NEW_LINE |
Count total set bits in all numbers from 1 to n | | def getSetBitsFromOneToN ( N ) : NEW_LINE INDENT two = 2 NEW_LINE ans = 0 NEW_LINE n = N NEW_LINE while ( n != 0 ) : NEW_LINE INDENT ans += int ( N / two ) * ( two >> 1 ) NEW_LINE if ( ( N & ( two - 1 ) ) > ( two >> 1 ) - 1 ) : NEW_LINE INDENT ans += ( N & ( two - 1 ) ) - ( two >> 1 ) + 1 NEW_LINE DEDENT two <<= 1 ; NEW_LINE n >>= 1 ; NEW_LINE DEDENT return ans NEW_LINE DEDENT |
Swap bits in a given number | Python program to swap bits in a given number ; Move all bits of first set to rightmost side ; Moce all bits of second set to rightmost side ; XOR the two sets ; Put the xor bits back to their original positions ; XOR the ' xor ' with the original number so that the two sets are swapped ; Driver code | def swapBits ( x , p1 , p2 , n ) : NEW_LINE INDENT set1 = ( x >> p1 ) & ( ( 1 << n ) - 1 ) NEW_LINE set2 = ( x >> p2 ) & ( ( 1 << n ) - 1 ) NEW_LINE xor = ( set1 ^ set2 ) NEW_LINE xor = ( xor << p1 ) | ( xor << p2 ) NEW_LINE result = x ^ xor NEW_LINE return result NEW_LINE DEDENT res = swapBits ( 28 , 0 , 3 , 2 ) NEW_LINE print ( " Result β = " , res ) NEW_LINE |
Swap bits in a given number | ; Setting bit at p1 position to 1 ; Setting bit at p2 position to 1 ; value1 and value2 will have 0 if num at the respective positions - p1 and p2 is 0. ; check if value1 and value2 are different i . e . at one position bit is set and other it is not ; if bit at p1 position is set ; unset bit at p1 position ; set bit at p2 position ; if bit at p2 position is set ; set bit at p2 position ; unset bit at p2 position ; return final result ; Driver code | def swapBits ( num , p1 , p2 , n ) : NEW_LINE INDENT shift1 = 0 NEW_LINE shift2 = 0 NEW_LINE value1 = 0 NEW_LINE value2 = 0 NEW_LINE while ( n > 0 ) : NEW_LINE INDENT shift1 = 1 << p1 NEW_LINE shift2 = 1 << p2 NEW_LINE value1 = ( ( num & shift1 ) ) NEW_LINE value2 = ( ( num & shift2 ) ) NEW_LINE if ( ( value1 == 0 and value2 != 0 ) or ( value2 == 0 and value1 != 0 ) ) : NEW_LINE INDENT if ( value1 != 0 ) : NEW_LINE INDENT num = num & ( ~ shift1 ) NEW_LINE num = num | shift2 NEW_LINE DEDENT else : NEW_LINE INDENT num = num & ( ~ shift2 ) NEW_LINE num = num | shift1 NEW_LINE DEDENT DEDENT p1 += 1 NEW_LINE p2 += 1 NEW_LINE n -= 1 NEW_LINE DEDENT return num NEW_LINE DEDENT res = swapBits ( 28 , 0 , 3 , 2 ) NEW_LINE print ( " Result β = " , res ) NEW_LINE |
Smallest of three integers without comparison operators | Python3 program to find Smallest of three integers without comparison operators ; Driver Code | def smallest ( x , y , z ) : NEW_LINE INDENT c = 0 NEW_LINE while ( x and y and z ) : NEW_LINE INDENT x = x - 1 NEW_LINE y = y - 1 NEW_LINE z = z - 1 NEW_LINE c = c + 1 NEW_LINE DEDENT return c NEW_LINE DEDENT x = 12 NEW_LINE y = 15 NEW_LINE z = 5 NEW_LINE print ( " Minimum β of β 3 β numbers β is " , smallest ( x , y , z ) ) NEW_LINE |
Smallest of three integers without comparison operators | Python3 implementation of above approach ; Function to find minimum of x and y ; Function to find minimum of 3 numbers x , y and z ; Driver code | CHAR_BIT = 8 NEW_LINE def min ( x , y ) : NEW_LINE INDENT return y + ( ( x - y ) & ( ( x - y ) >> ( 32 * CHAR_BIT - 1 ) ) ) NEW_LINE DEDENT def smallest ( x , y , z ) : NEW_LINE INDENT return min ( x , min ( y , z ) ) NEW_LINE DEDENT x = 12 NEW_LINE y = 15 NEW_LINE z = 5 NEW_LINE print ( " Minimum β of β 3 β numbers β is β " , smallest ( x , y , z ) ) NEW_LINE |
Smallest of three integers without comparison operators | Using division operator to find minimum of three numbers ; Same as " if β ( y β < β x ) " ; Driver Code | def smallest ( x , y , z ) : NEW_LINE INDENT if ( not ( y / x ) ) : NEW_LINE INDENT return y if ( not ( y / z ) ) else z NEW_LINE DEDENT return x if ( not ( x / z ) ) else z NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT x = 78 NEW_LINE y = 88 NEW_LINE z = 68 NEW_LINE print ( " Minimum β of β 3 β numbers β is " , smallest ( x , y , z ) ) NEW_LINE DEDENT |
A Boolean Array Puzzle | ; Driver code | def changeToZero ( a ) : NEW_LINE INDENT a [ a [ 1 ] ] = a [ not a [ 1 ] ] NEW_LINE return a NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT a = [ 1 , 0 ] NEW_LINE a = changeToZero ( a ) ; NEW_LINE print ( " β arr [ 0 ] β = β " + str ( a [ 0 ] ) ) NEW_LINE print ( " β arr [ 1 ] β = β " + str ( a [ 1 ] ) ) NEW_LINE DEDENT |
Next higher number with same number of set bits | This function returns next higher number with same number of set bits as x . ; right most set bit ; reset the pattern and set next higher bit left part of x will be here ; nextHigherOneBit is now part [ D ] of the above explanation . isolate the pattern ; right adjust pattern ; correction factor ; rightOnesPattern is now part [ A ] of the above explanation . integrate new pattern ( Add [ D ] and [ A ] ) ; Driver Code | def snoob ( x ) : NEW_LINE INDENT next = 0 NEW_LINE if ( x ) : NEW_LINE INDENT rightOne = x & - ( x ) NEW_LINE nextHigherOneBit = x + int ( rightOne ) NEW_LINE rightOnesPattern = x ^ int ( nextHigherOneBit ) NEW_LINE rightOnesPattern = ( int ( rightOnesPattern ) / int ( rightOne ) ) NEW_LINE rightOnesPattern = int ( rightOnesPattern ) >> 2 NEW_LINE next = nextHigherOneBit | rightOnesPattern NEW_LINE DEDENT return next NEW_LINE DEDENT x = 156 NEW_LINE print ( " Next β higher β number β with β " + " same β number β of β set β bits β is " , snoob ( x ) ) NEW_LINE |
Add 1 to a given number | Python3 code to add 1 one to a given number ; Flip all the set bits until we find a 0 ; flip the rightmost 0 bit ; Driver program | def addOne ( x ) : NEW_LINE INDENT m = 1 ; NEW_LINE while ( x & m ) : NEW_LINE INDENT x = x ^ m NEW_LINE m <<= 1 NEW_LINE DEDENT x = x ^ m NEW_LINE return x NEW_LINE DEDENT n = 13 NEW_LINE print addOne ( n ) NEW_LINE |
Add 1 to a given number | Python3 code to add 1 to a given number ; Driver program | def addOne ( x ) : NEW_LINE INDENT return ( - ( ~ x ) ) ; NEW_LINE DEDENT print ( addOne ( 13 ) ) NEW_LINE |
Multiply a given Integer with 3.5 | Python 3 program to multiply a number with 3.5 ; Driver program to test above functions | def multiplyWith3Point5 ( x ) : NEW_LINE INDENT return ( x << 1 ) + x + ( x >> 1 ) NEW_LINE DEDENT x = 4 NEW_LINE print ( multiplyWith3Point5 ( x ) ) NEW_LINE |
Turn off the rightmost set bit | unsets the rightmost set bit of n and returns the result ; Driver code | def fun ( n ) : NEW_LINE INDENT return n & ( n - 1 ) NEW_LINE DEDENT n = 7 NEW_LINE print ( " The β number β after β unsetting β the β rightmost β set β bit " , fun ( n ) ) NEW_LINE |
Find whether a given number is a power of 4 or not | Function to check if x is power of 4 ; Driver code | def isPowerOfFour ( n ) : NEW_LINE INDENT if ( n == 0 ) : NEW_LINE INDENT return False NEW_LINE DEDENT while ( n != 1 ) : NEW_LINE INDENT if ( n % 4 != 0 ) : NEW_LINE INDENT return False NEW_LINE DEDENT n = n // 4 NEW_LINE DEDENT return True NEW_LINE DEDENT test_no = 64 NEW_LINE if ( isPowerOfFour ( 64 ) ) : NEW_LINE INDENT print ( test_no , ' is β a β power β of β 4' ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( test_no , ' is β not β a β power β of β 4' ) NEW_LINE DEDENT |
Find whether a given number is a power of 4 or not | Function to check if x is power of 4 ; Check if there is only one bit set in n ; count 0 bits before set bit ; If count is even then return true else false ; Driver code | def isPowerOfFour ( n ) : NEW_LINE INDENT count = 0 NEW_LINE if ( n and ( not ( n & ( n - 1 ) ) ) ) : NEW_LINE INDENT while ( n > 1 ) : NEW_LINE INDENT n >>= 1 NEW_LINE count += 1 NEW_LINE DEDENT if ( count % 2 == 0 ) : NEW_LINE INDENT return True NEW_LINE DEDENT else : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT DEDENT test_no = 64 NEW_LINE if ( isPowerOfFour ( 64 ) ) : NEW_LINE INDENT print ( test_no , ' is β a β power β of β 4' ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( test_no , ' is β not β a β power β of β 4' ) NEW_LINE DEDENT |
Find whether a given number is a power of 4 or not | Python3 program to check if given number is power of 4 or not ; Driver code | def isPowerOfFour ( n ) : NEW_LINE INDENT return ( n != 0 and ( ( n & ( n - 1 ) ) == 0 ) and not ( n & 0xAAAAAAAA ) ) ; NEW_LINE DEDENT test_no = 64 ; NEW_LINE if ( isPowerOfFour ( test_no ) ) : NEW_LINE INDENT print ( test_no , " is β a β power β of β 4" ) ; NEW_LINE DEDENT else : NEW_LINE INDENT print ( test_no , " is β not β a β power β of β 4" ) ; NEW_LINE DEDENT |
Find whether a given number is a power of 4 or not | Python3 program to check if given number is power of 4 or not ; 0 is not considered as a power of 4 ; Driver code | import math NEW_LINE def logn ( n , r ) : NEW_LINE INDENT return math . log ( n ) / math . log ( r ) NEW_LINE DEDENT def isPowerOfFour ( n ) : NEW_LINE INDENT if ( n == 0 ) : NEW_LINE INDENT return False NEW_LINE DEDENT return ( math . floor ( logn ( n , 4 ) ) == math . ceil ( logn ( n , 4 ) ) ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT test_no = 64 NEW_LINE if ( isPowerOfFour ( test_no ) ) : NEW_LINE INDENT print ( test_no , " β is β a β power β of β 4" ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( test_no , " β is β not β a β power β of β 4" ) NEW_LINE DEDENT DEDENT |
Find whether a given number is a power of 4 or not | Python3 program to check if given number is power of 4 or not ; Driver code | import math NEW_LINE def isPowerOfFour ( n ) : NEW_LINE INDENT return ( n > 0 and 4 ** int ( math . log ( n , 4 ) ) == n ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT test_no = 64 NEW_LINE if ( isPowerOfFour ( test_no ) ) : NEW_LINE INDENT print ( test_no , " β is β a β power β of β 4" ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( test_no , " β is β not β a β power β of β 4" ) NEW_LINE DEDENT DEDENT |
Compute the minimum or maximum of two integers without branching | Function to find minimum of x and y ; Function to find maximum of x and y ; Driver program to test above functions | def min ( x , y ) : NEW_LINE INDENT return y ^ ( ( x ^ y ) & - ( x < y ) ) NEW_LINE DEDENT def max ( x , y ) : NEW_LINE INDENT return x ^ ( ( x ^ y ) & - ( x < y ) ) NEW_LINE DEDENT x = 15 NEW_LINE y = 6 NEW_LINE print ( " Minimum β of " , x , " and " , y , " is " , end = " β " ) NEW_LINE print ( min ( x , y ) ) NEW_LINE print ( " Maximum β of " , x , " and " , y , " is " , end = " β " ) NEW_LINE print ( max ( x , y ) ) NEW_LINE |
Compute the minimum or maximum of two integers without branching | Python3 implementation of the approach ; Function to find minimum of x and y ; Function to find maximum of x and y ; Driver code | import sys ; NEW_LINE CHAR_BIT = 8 ; NEW_LINE INT_BIT = sys . getsizeof ( int ( ) ) ; NEW_LINE def Min ( x , y ) : NEW_LINE INDENT return y + ( ( x - y ) & ( ( x - y ) >> ( INT_BIT * CHAR_BIT - 1 ) ) ) ; NEW_LINE DEDENT def Max ( x , y ) : NEW_LINE INDENT return x - ( ( x - y ) & ( ( x - y ) >> ( INT_BIT * CHAR_BIT - 1 ) ) ) ; NEW_LINE DEDENT x = 15 ; NEW_LINE y = 6 ; NEW_LINE print ( " Minimum β of " , x , " and " , y , " is " , Min ( x , y ) ) ; NEW_LINE print ( " Maximum β of " , x , " and " , y , " is " , Max ( x , y ) ) ; NEW_LINE |
Compute the minimum or maximum of two integers without branching | absbit32 function ; max function ; min function ; Driver code | def absbit32 ( x , y ) : NEW_LINE INDENT sub = x - y NEW_LINE mask = ( sub >> 31 ) NEW_LINE return ( sub ^ mask ) - mask NEW_LINE DEDENT def max ( x , y ) : NEW_LINE INDENT abs = absbit32 ( x , y ) NEW_LINE return ( x + y + abs ) // 2 NEW_LINE DEDENT def min ( x , y ) : NEW_LINE INDENT abs = absbit32 ( x , y ) NEW_LINE return ( x + y - abs ) // 2 NEW_LINE DEDENT print ( max ( 2 , 3 ) ) NEW_LINE print ( max ( 2 , - 3 ) ) NEW_LINE print ( max ( - 2 , - 3 ) ) NEW_LINE print ( min ( 2 , 3 ) ) NEW_LINE print ( min ( 2 , - 3 ) ) NEW_LINE print ( min ( - 2 , - 3 ) ) NEW_LINE |
Find the two non | This function sets the values of * x and * y to non - repeating elements in an array arr [ ] of size n ; Xor all the elements of the array all the elements occuring twice will cancel out each other remaining two unnique numbers will be xored ; Bitwise & the sum with it ' s β 2' s Complement Bitwise & will give us the sum containing only the rightmost set bit ; sum1 and sum2 will contains 2 unique elements elements initialized with 0 box number xored with 0 is number itself ; Traversing the array again ; Bitwise & the arr [ i ] with the sum Two possibilities either result == 0 or result > 0 ; If result > 0 then arr [ i ] xored with the sum1 ; If result == 0 then arr [ i ] xored with sum2 ; Print the the two unique numbers ; Driver Code | def UniqueNumbers2 ( arr , n ) : NEW_LINE INDENT sums = 0 NEW_LINE for i in range ( 0 , n ) : NEW_LINE INDENT sums = ( sums ^ arr [ i ] ) NEW_LINE DEDENT sums = ( sums & - sums ) NEW_LINE sum1 = 0 NEW_LINE sum2 = 0 NEW_LINE for i in range ( 0 , len ( arr ) ) : NEW_LINE INDENT if ( arr [ i ] & sums ) > 0 : NEW_LINE sum1 = ( sum1 ^ arr [ i ] ) NEW_LINE else : NEW_LINE sum2 = ( sum2 ^ arr [ i ] ) NEW_LINE DEDENT print ( " The β non - repeating β elements β are β " , sum1 , " β and β " , sum2 ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 2 , 3 , 7 , 9 , 11 , 2 , 3 , 11 ] NEW_LINE n = len ( arr ) NEW_LINE UniqueNumbers2 ( arr , n ) NEW_LINE DEDENT |
Find the Number Occurring Odd Number of Times | function to find the element occurring odd number of times ; driver code ; Function calling | def getOddOccurrence ( arr , arr_size ) : NEW_LINE INDENT for i in range ( 0 , arr_size ) : NEW_LINE INDENT count = 0 NEW_LINE for j in range ( 0 , arr_size ) : NEW_LINE INDENT if arr [ i ] == arr [ j ] : NEW_LINE INDENT count += 1 NEW_LINE DEDENT DEDENT if ( count % 2 != 0 ) : NEW_LINE INDENT return arr [ i ] NEW_LINE DEDENT DEDENT return - 1 NEW_LINE DEDENT arr = [ 2 , 3 , 5 , 4 , 5 , 2 , 4 , 3 , 5 , 2 , 4 , 4 , 2 ] NEW_LINE n = len ( arr ) NEW_LINE print ( getOddOccurrence ( arr , n ) ) NEW_LINE |
Find the Number Occurring Odd Number of Times | function to find the element occurring odd number of times ; Putting all elements into the HashMap ; Iterate through HashMap to check an element occurring odd number of times and return it ; Driver code | def getOddOccurrence ( arr , size ) : NEW_LINE INDENT Hash = dict ( ) NEW_LINE for i in range ( size ) : NEW_LINE INDENT Hash [ arr [ i ] ] = Hash . get ( arr [ i ] , 0 ) + 1 ; NEW_LINE DEDENT for i in Hash : NEW_LINE INDENT if ( Hash [ i ] % 2 != 0 ) : NEW_LINE INDENT return i NEW_LINE DEDENT DEDENT return - 1 NEW_LINE DEDENT arr = [ 2 , 3 , 5 , 4 , 5 , 2 , 4 , 3 , 5 , 2 , 4 , 4 , 2 ] NEW_LINE n = len ( arr ) NEW_LINE print ( getOddOccurrence ( arr , n ) ) NEW_LINE |
Count number of bits to be flipped to convert A to B | Function that count set bits ; Function that return count of flipped number ; Return count of set bits in a XOR b ; Driver code | def countSetBits ( n ) : NEW_LINE INDENT count = 0 NEW_LINE while n : NEW_LINE INDENT count += 1 NEW_LINE n &= ( n - 1 ) NEW_LINE DEDENT return count NEW_LINE DEDENT def FlippedCount ( a , b ) : NEW_LINE INDENT return countSetBits ( a ^ b ) NEW_LINE DEDENT a = 10 NEW_LINE b = 20 NEW_LINE print ( FlippedCount ( a , b ) ) NEW_LINE |
Position of rightmost set bit | Python Code for Position of rightmost set bit ; driver code | import math NEW_LINE def getFirstSetBitPos ( n ) : NEW_LINE INDENT return math . log2 ( n & - n ) + 1 NEW_LINE DEDENT n = 12 NEW_LINE print ( int ( getFirstSetBitPos ( n ) ) ) NEW_LINE |
Position of rightmost set bit | function to find the rightmost set bit ; Position variable initialize with 1 m variable is used to check the set bit ; left shift ; Driver Code ; function call | def PositionRightmostSetbit ( n ) : NEW_LINE INDENT position = 1 NEW_LINE m = 1 NEW_LINE while ( not ( n & m ) ) : NEW_LINE INDENT m = m << 1 NEW_LINE position += 1 NEW_LINE DEDENT return position NEW_LINE DEDENT n = 16 NEW_LINE print ( PositionRightmostSetbit ( n ) ) NEW_LINE |
Position of rightmost set bit | Python 3 implementation of above approach ; counting the position of first set bit ; Driver code | INT_SIZE = 32 NEW_LINE def Right_most_setbit ( num ) : NEW_LINE INDENT pos = 1 NEW_LINE for i in range ( INT_SIZE ) : NEW_LINE INDENT if not ( num & ( 1 << i ) ) : NEW_LINE INDENT pos += 1 NEW_LINE DEDENT else : NEW_LINE INDENT break NEW_LINE DEDENT DEDENT return pos NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT num = 18 NEW_LINE pos = Right_most_setbit ( num ) NEW_LINE print ( pos ) NEW_LINE DEDENT |
Position of rightmost set bit | Program to find position of rightmost set bit ; Iterate till number > 0 ; Checking if last bit is set ; Increment position and right shift number ; set bit not found . ; Driver Code ; Function call | def PositionRightmostSetbit ( n ) : NEW_LINE INDENT p = 1 NEW_LINE while ( n > 0 ) : NEW_LINE INDENT if ( n & 1 ) : NEW_LINE return p NEW_LINE p += 1 NEW_LINE n = n >> 1 NEW_LINE DEDENT return - 1 ; NEW_LINE DEDENT n = 18 NEW_LINE pos = PositionRightmostSetbit ( n ) NEW_LINE if ( pos != - 1 ) : NEW_LINE INDENT print ( pos ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( 0 ) NEW_LINE DEDENT |
Binary representation of a given number | bin function ; Driver Code | def bin ( n ) : NEW_LINE INDENT i = 1 << 31 NEW_LINE while ( i > 0 ) : NEW_LINE INDENT if ( ( n & i ) != 0 ) : NEW_LINE INDENT print ( "1" , end = " " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( "0" , end = " " ) NEW_LINE DEDENT i = i // 2 NEW_LINE DEDENT DEDENT bin ( 7 ) NEW_LINE print ( ) NEW_LINE bin ( 4 ) NEW_LINE |
Binary representation of a given number | Function to convert decimal to binary number ; Driver code | def bin ( n ) : NEW_LINE INDENT if ( n > 1 ) : NEW_LINE INDENT bin ( n >> 1 ) NEW_LINE DEDENT print ( n & 1 , end = " " ) NEW_LINE DEDENT bin ( 131 ) NEW_LINE print ( ) NEW_LINE bin ( 3 ) NEW_LINE |
Swap all odd and even bits | Function for swapping even and odd bits ; Get all even bits of x ; Get all odd bits of x ; Right shift even bits ; Left shift odd bits ; Combine even and odd bits ; 00010111 ; Output is 43 ( 00101011 ) | def swapBits ( x ) : NEW_LINE INDENT even_bits = x & 0xAAAAAAAA NEW_LINE odd_bits = x & 0x55555555 NEW_LINE even_bits >>= 1 NEW_LINE odd_bits <<= 1 NEW_LINE return ( even_bits odd_bits ) NEW_LINE DEDENT x = 23 NEW_LINE print ( swapBits ( x ) ) NEW_LINE |
Find position of the only set bit | A utility function to check whether n is power of 2 or not . ; Returns position of the only set bit in 'n ; Iterate through bits of n till we find a set bit i & n will be non - zero only when ' i ' and ' n ' have a set bit at same position ; Unset current bit and set the next bit in 'i ; increment position ; Driver Code | def isPowerOfTwo ( n ) : NEW_LINE INDENT return ( True if ( n > 0 and ( ( n & ( n - 1 ) ) > 0 ) ) else False ) ; NEW_LINE DEDENT def findPosition ( n ) : NEW_LINE INDENT if ( isPowerOfTwo ( n ) == True ) : NEW_LINE INDENT return - 1 ; NEW_LINE DEDENT i = 1 ; NEW_LINE pos = 1 ; NEW_LINE while ( ( i & n ) == 0 ) : NEW_LINE INDENT i = i << 1 ; NEW_LINE pos += 1 ; NEW_LINE DEDENT return pos ; NEW_LINE DEDENT n = 16 ; NEW_LINE pos = findPosition ( n ) ; NEW_LINE if ( pos == - 1 ) : NEW_LINE INDENT print ( " n β = " , n , " , β Invalid β number " ) ; NEW_LINE DEDENT else : NEW_LINE INDENT print ( " n β = " , n , " , β Position β " , pos ) ; NEW_LINE DEDENT n = 12 ; NEW_LINE pos = findPosition ( n ) ; NEW_LINE if ( pos == - 1 ) : NEW_LINE INDENT print ( " n β = " , n , " , β Invalid β number " ) ; NEW_LINE DEDENT else : NEW_LINE INDENT print ( " n β = " , n , " , β Position β " , pos ) ; NEW_LINE DEDENT n = 128 ; NEW_LINE pos = findPosition ( n ) ; NEW_LINE if ( pos == - 1 ) : NEW_LINE INDENT print ( " n β = " , n , " , β Invalid β number " ) ; NEW_LINE DEDENT else : NEW_LINE INDENT print ( " n β = " , n , " , β Position β " , pos ) ; NEW_LINE DEDENT |
Find position of the only set bit | A utility function to check whether n is power of 2 or not ; Returns position of the only set bit in 'n ; One by one move the only set bit to right till it reaches end ; increment count of shifts ; Driver program to test above function | def isPowerOfTwo ( n ) : NEW_LINE INDENT return ( n and ( not ( n & ( n - 1 ) ) ) ) NEW_LINE DEDENT def findPosition ( n ) : NEW_LINE INDENT if not isPowerOfTwo ( n ) : NEW_LINE INDENT return - 1 NEW_LINE DEDENT count = 0 NEW_LINE while ( n ) : NEW_LINE INDENT n = n >> 1 NEW_LINE count += 1 NEW_LINE DEDENT return count NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT n = 0 NEW_LINE pos = findPosition ( n ) NEW_LINE if pos == - 1 : NEW_LINE INDENT print ( " n β = " , n , " Invalid β number " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " n β = " , n , " Position " , pos ) NEW_LINE DEDENT n = 12 NEW_LINE pos = findPosition ( n ) NEW_LINE if pos == - 1 : NEW_LINE INDENT print ( " n β = " , n , " Invalid β number " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " n β = " , n , " Position " , pos ) NEW_LINE DEDENT n = 128 NEW_LINE pos = findPosition ( n ) NEW_LINE if pos == - 1 : NEW_LINE INDENT print ( " n β = " , n , " Invalid β number " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " n β = " , n , " Position " , pos ) NEW_LINE DEDENT DEDENT |
How to swap two numbers without using a temporary variable ? | Python3 program to swap two numbers without using temporary variable ; code to swap x ' β and β ' y ' x now becomes 50 ; y becomes 10 ; x becomes 5 | x = 10 NEW_LINE y = 5 NEW_LINE x = x * y NEW_LINE y = x // y ; NEW_LINE x = x // y ; NEW_LINE print ( " After β Swapping : β x β = " , x , " β y β = " , y ) ; NEW_LINE |
How to swap two numbers without using a temporary variable ? | Python3 code to swap using XOR ; Code to swap ' x ' and ' y ' x now becomes 15 ( 1111 ) ; y becomes 10 ( 1010 ) ; x becomes 5 ( 0101 ) | x = 10 NEW_LINE y = 5 NEW_LINE x = x ^ y ; NEW_LINE y = x ^ y ; NEW_LINE x = x ^ y ; NEW_LINE print ( " After β Swapping : β x β = β " , x , " β y β = " , y ) NEW_LINE |
How to swap two numbers without using a temporary variable ? | Swap function ; Driver code | def swap ( xp , yp ) : NEW_LINE INDENT xp [ 0 ] = xp [ 0 ] ^ yp [ 0 ] NEW_LINE yp [ 0 ] = xp [ 0 ] ^ yp [ 0 ] NEW_LINE xp [ 0 ] = xp [ 0 ] ^ yp [ 0 ] NEW_LINE DEDENT x = [ 10 ] NEW_LINE swap ( x , x ) NEW_LINE print ( " After β swap ( & x , β & x ) : β x β = β " , x [ 0 ] ) NEW_LINE |
How to swap two numbers without using a temporary variable ? | Function to swap the numbers ; Same as a = a + b ; Same as b = a - b ; Same as a = a - b ; Driver code ; Function call | def swap ( a , b ) : NEW_LINE INDENT a = ( a & b ) + ( a b ) NEW_LINE b = a + ( ~ b ) + 1 NEW_LINE a = a + ( ~ b ) + 1 NEW_LINE print ( " After β Swapping : β a β = β " , a , " , β b β = β " , b ) NEW_LINE DEDENT a = 5 NEW_LINE b = 10 NEW_LINE swap ( a , b ) NEW_LINE |
N Queen Problem using Branch And Bound | Python3 program to solve N Queen Problem using Branch or Bound ; A utility function to pri nt solution ; A Optimized function to check if a queen can be placed on board [ row ] [ col ] ; A recursive utility function to solve N Queen problem ; base case : If all queens are placed then return True ; Consider this column and try placing this queen in all rows one by one ; Check if queen can be placed on board [ i ] [ col ] ; Place this queen in board [ i ] [ col ] ; recur to place rest of the queens ; Remove queen from board [ i ] [ col ] ; If queen can not be place in any row in this colum col then return False ; This function solves the N Queen problem using Branch or Bound . It mainly uses solveNQueensUtil ( ) to solve the problem . It returns False if queens cannot be placed , otherwise return True or prints placement of queens in the form of 1 s . Please note that there may be more than one solutions , this function prints one of the feasible solutions . ; helper matrices ; arrays to tell us which rows are occupied ; keep two arrays to tell us which diagonals are occupied ; initialize helper matrices ; solution found ; Driver Cde | N = 8 NEW_LINE def printSolution ( board ) : NEW_LINE INDENT for i in range ( N ) : NEW_LINE INDENT for j in range ( N ) : NEW_LINE INDENT print ( board [ i ] [ j ] , end = " β " ) NEW_LINE DEDENT print ( ) NEW_LINE DEDENT DEDENT def isSafe ( row , col , slashCode , backslashCode , rowLookup , slashCodeLookup , backslashCodeLookup ) : NEW_LINE INDENT if ( slashCodeLookup [ slashCode [ row ] [ col ] ] or backslashCodeLookup [ backslashCode [ row ] [ col ] ] or rowLookup [ row ] ) : NEW_LINE INDENT return False NEW_LINE DEDENT return True NEW_LINE DEDENT def solveNQueensUtil ( board , col , slashCode , backslashCode , rowLookup , slashCodeLookup , backslashCodeLookup ) : NEW_LINE INDENT if ( col >= N ) : NEW_LINE INDENT return True NEW_LINE DEDENT for i in range ( N ) : NEW_LINE INDENT if ( isSafe ( i , col , slashCode , backslashCode , rowLookup , slashCodeLookup , backslashCodeLookup ) ) : NEW_LINE INDENT board [ i ] [ col ] = 1 NEW_LINE rowLookup [ i ] = True NEW_LINE slashCodeLookup [ slashCode [ i ] [ col ] ] = True NEW_LINE backslashCodeLookup [ backslashCode [ i ] [ col ] ] = True NEW_LINE if ( solveNQueensUtil ( board , col + 1 , slashCode , backslashCode , rowLookup , slashCodeLookup , backslashCodeLookup ) ) : NEW_LINE INDENT return True NEW_LINE DEDENT board [ i ] [ col ] = 0 NEW_LINE rowLookup [ i ] = False NEW_LINE slashCodeLookup [ slashCode [ i ] [ col ] ] = False NEW_LINE backslashCodeLookup [ backslashCode [ i ] [ col ] ] = False NEW_LINE DEDENT DEDENT return False NEW_LINE DEDENT def solveNQueens ( ) : NEW_LINE INDENT board = [ [ 0 for i in range ( N ) ] for j in range ( N ) ] NEW_LINE slashCode = [ [ 0 for i in range ( N ) ] for j in range ( N ) ] NEW_LINE backslashCode = [ [ 0 for i in range ( N ) ] for j in range ( N ) ] NEW_LINE rowLookup = [ False ] * N NEW_LINE x = 2 * N - 1 NEW_LINE slashCodeLookup = [ False ] * x NEW_LINE backslashCodeLookup = [ False ] * x NEW_LINE for rr in range ( N ) : NEW_LINE INDENT for cc in range ( N ) : NEW_LINE INDENT slashCode [ rr ] [ cc ] = rr + cc NEW_LINE backslashCode [ rr ] [ cc ] = rr - cc + 7 NEW_LINE DEDENT DEDENT if ( solveNQueensUtil ( board , 0 , slashCode , backslashCode , rowLookup , slashCodeLookup , backslashCodeLookup ) == False ) : NEW_LINE INDENT print ( " Solution β does β not β exist " ) NEW_LINE return False NEW_LINE DEDENT printSolution ( board ) NEW_LINE return True NEW_LINE DEDENT solveNQueens ( ) NEW_LINE |
Check a given sentence for a given set of simple grammer rules | Method to check a given sentence for given rules ; Calculate the length of the string . ; Check that the first character lies in [ A - Z ] . Otherwise return false . ; If the last character is not a full stop ( . ) no need to check further . ; Maintain 2 states . Previous and current state based on which vertex state you are . Initialise both with 0 = start state . ; Keep the index to the next character in the string . ; Loop to go over the string . ; Set states according to the input characters in the string and the rule defined in the description . If current character is [ A - Z ] . Set current state as 0. ; If current character is a space . Set current state as 1. ; If current character is a space . Set current state as 2. ; If current character is a space . Set current state as 3. ; Validates all current state with previous state for the rules in the description of the problem . ; If we have reached last state and previous state is not 1 , then check next character . If next character is ' \0' , then return true , else false ; Set previous state as current state before going over to the next character . ; Driver program | def checkSentence ( string ) : NEW_LINE INDENT length = len ( string ) NEW_LINE if string [ 0 ] < ' A ' or string [ 0 ] > ' Z ' : NEW_LINE INDENT return False NEW_LINE DEDENT if string [ length - 1 ] != ' . ' : NEW_LINE INDENT return False NEW_LINE DEDENT prev_state = 0 NEW_LINE curr_state = 0 NEW_LINE index = 1 NEW_LINE while ( string [ index ] ) : NEW_LINE INDENT if string [ index ] >= ' A ' and string [ index ] <= ' Z ' : NEW_LINE INDENT curr_state = 0 NEW_LINE DEDENT elif string [ index ] == ' β ' : NEW_LINE INDENT curr_state = 1 NEW_LINE DEDENT elif string [ index ] >= ' a ' and string [ index ] <= ' z ' : NEW_LINE INDENT curr_state = 2 NEW_LINE DEDENT elif string [ index ] == ' . ' : NEW_LINE INDENT curr_state = 3 NEW_LINE DEDENT if prev_state == curr_state and curr_state != 2 : NEW_LINE INDENT return False NEW_LINE DEDENT if prev_state == 2 and curr_state == 0 : NEW_LINE INDENT return False NEW_LINE DEDENT if curr_state == 3 and prev_state != 1 : NEW_LINE INDENT return True NEW_LINE DEDENT index += 1 NEW_LINE prev_state = curr_state NEW_LINE DEDENT return False NEW_LINE DEDENT string = [ " I β love β cinema . " , " The β vertex β is β S . " , " I β am β single . " , " My β name β is β KG . " , " I β lovE β cinema . " , " GeeksQuiz . β is β a β quiz β site . " , " I β love β Geeksquiz β and β Geeksforgeeks . " , " β You β are β my β friend . " , " I β love β cinema " ] NEW_LINE string_size = len ( string ) NEW_LINE for i in xrange ( string_size ) : NEW_LINE INDENT if checkSentence ( string [ i ] ) : NEW_LINE INDENT print " \ " " + string [ i ] + " \ " β is β correct " NEW_LINE DEDENT else : NEW_LINE INDENT print " \ " " + string [ i ] + " \ " β is β incorrect " NEW_LINE DEDENT DEDENT |
Find Index of 0 to be replaced with 1 to get longest continuous sequence of 1 s in a binary array | Returns index of 0 to be replaced with 1 to get longest continuous sequence of 1 s . If there is no 0 in array , then it returns - 1. ; for maximum number of 1 around a zero ; for storing result ; index of previous zero ; index of previous to previous zero ; Traverse the input array ; If current element is 0 , then calculate the difference between curr and prev_prev_zero ; Update result if count of 1 s around prev_zero is more ; Update for next iteration ; Check for the last encountered zero ; Driver program | def maxOnesIndex ( arr , n ) : NEW_LINE INDENT max_count = 0 NEW_LINE max_index = 0 NEW_LINE prev_zero = - 1 NEW_LINE prev_prev_zero = - 1 NEW_LINE for curr in range ( n ) : NEW_LINE INDENT if ( arr [ curr ] == 0 ) : NEW_LINE INDENT if ( curr - prev_prev_zero > max_count ) : NEW_LINE INDENT max_count = curr - prev_prev_zero NEW_LINE max_index = prev_zero NEW_LINE DEDENT prev_prev_zero = prev_zero NEW_LINE prev_zero = curr NEW_LINE DEDENT DEDENT if ( n - prev_prev_zero > max_count ) : NEW_LINE INDENT max_index = prev_zero NEW_LINE DEDENT return max_index NEW_LINE DEDENT arr = [ 1 , 1 , 0 , 0 , 1 , 0 , 1 , 1 , 1 , 0 , 1 , 1 , 1 ] NEW_LINE n = len ( arr ) NEW_LINE print ( " Index β of β 0 β to β be β replaced β is β " , maxOnesIndex ( arr , n ) ) NEW_LINE |
Length of the largest subarray with contiguous elements | Set 1 | Utility functions to find minimum and maximum of two elements ; Returns length of the longest contiguous subarray ; Initialize result ; Initialize min and max for all subarrays starting with i ; Consider all subarrays starting with i and ending with j ; Update min and max in this subarray if needed ; If current subarray has all contiguous elements ; Return result ; Driver Code | def min ( x , y ) : NEW_LINE INDENT return x if ( x < y ) else y NEW_LINE DEDENT def max ( x , y ) : NEW_LINE INDENT return x if ( x > y ) else y NEW_LINE DEDENT def findLength ( arr , n ) : NEW_LINE INDENT max_len = 1 NEW_LINE for i in range ( n - 1 ) : NEW_LINE INDENT mn = arr [ i ] NEW_LINE mx = arr [ i ] NEW_LINE for j in range ( i + 1 , n ) : NEW_LINE INDENT mn = min ( mn , arr [ j ] ) NEW_LINE mx = max ( mx , arr [ j ] ) NEW_LINE if ( ( mx - mn ) == j - i ) : NEW_LINE INDENT max_len = max ( max_len , mx - mn + 1 ) NEW_LINE DEDENT DEDENT DEDENT return max_len NEW_LINE DEDENT arr = [ 1 , 56 , 58 , 57 , 90 , 92 , 94 , 93 , 91 , 45 ] NEW_LINE n = len ( arr ) NEW_LINE print ( " Length β of β the β longest β contiguous β subarray β is β " , findLength ( arr , n ) ) NEW_LINE |
Print all increasing sequences of length k from first n natural numbers | A utility function to print contents of arr [ 0. . k - 1 ] ; A recursive function to print all increasing sequences of first n natural numbers . Every sequence should be length k . The array arr [ ] is used to store current sequence . ; If length of current increasing sequence becomes k , print it ; Decide the starting number to put at current position : If length is 0 , then there are no previous elements in arr [ ] . So start putting new numbers with 1. If length is not 0 , then start from value of previous element plus 1. ; Increase length ; Put all numbers ( which are greater than the previous element ) at new position . ; This is important . The variable ' len ' is shared among all function calls in recursion tree . Its value must be brought back before next iteration of while loop ; This function prints all increasing sequences of first n natural numbers . The length of every sequence must be k . This function mainly uses printSeqUtil ( ) ; An array to store individual sequences ; Initial length of current sequence ; Driver Code | def printArr ( arr , k ) : NEW_LINE INDENT for i in range ( k ) : NEW_LINE INDENT print ( arr [ i ] , end = " β " ) ; NEW_LINE DEDENT print ( ) ; NEW_LINE DEDENT def printSeqUtil ( n , k , len1 , arr ) : NEW_LINE INDENT if ( len1 == k ) : NEW_LINE INDENT printArr ( arr , k ) ; NEW_LINE return ; NEW_LINE DEDENT i = 1 if ( len1 == 0 ) else ( arr [ len1 - 1 ] + 1 ) ; NEW_LINE len1 += 1 ; NEW_LINE while ( i <= n ) : NEW_LINE INDENT arr [ len1 - 1 ] = i ; NEW_LINE printSeqUtil ( n , k , len1 , arr ) ; NEW_LINE i += 1 ; NEW_LINE DEDENT len1 -= 1 ; NEW_LINE DEDENT def printSeq ( n , k ) : NEW_LINE INDENT arr = [ 0 ] * k ; NEW_LINE len1 = 0 ; NEW_LINE printSeqUtil ( n , k , len1 , arr ) ; NEW_LINE DEDENT k = 3 ; NEW_LINE n = 7 ; NEW_LINE printSeq ( n , k ) ; NEW_LINE |
Given two strings , find if first string is a subsequence of second | Returns true if str1 [ ] is a subsequence of str2 [ ] . ; Base Cases ; If last characters of two strings are matching ; If last characters are not matching ; Driver program to test the above function | def isSubSequence ( string1 , string2 , m , n ) : NEW_LINE INDENT if m == 0 : NEW_LINE INDENT return True NEW_LINE DEDENT if n == 0 : NEW_LINE INDENT return False NEW_LINE DEDENT if string1 [ m - 1 ] == string2 [ n - 1 ] : NEW_LINE INDENT return isSubSequence ( string1 , string2 , m - 1 , n - 1 ) NEW_LINE DEDENT return isSubSequence ( string1 , string2 , m , n - 1 ) NEW_LINE DEDENT string1 = " gksrek " NEW_LINE string2 = " geeksforgeeks " NEW_LINE if isSubSequence ( string1 , string2 , len ( string1 ) , len ( string2 ) ) : NEW_LINE INDENT print " Yes " NEW_LINE DEDENT else : NEW_LINE INDENT print " No " NEW_LINE DEDENT |
Find a sorted subsequence of size 3 in linear time | Python3 Program for above approach ; Function to find the triplet ; If number of elements < 3 then no triplets are possible ; Track best sequence length ( not current sequence length ) ; min number in array ; Least max number in best sequence i . e . track arr [ j ] ( e . g . in array { 1 , 5 , 3 } our best sequence would be { 1 , 3 } with arr [ j ] = 3 ) ; Save arr [ i ] ; Iterate from 1 to nums . size ( ) ; This condition is only hit when current sequence size is 2 ; Update best sequence max number to a smaller value ( i . e . we 've found a smaller value for arr[j]) ; Store best sequence start value i . e . arr [ i ] ; Increase best sequence length & save next number in our triplet ; We 've found our arr[k]! Print the output ; No triplet found ; Driver Code ; Function Call | import sys NEW_LINE def find3Numbers ( nums ) : NEW_LINE INDENT if ( len ( nums ) < 3 ) : NEW_LINE INDENT print ( " No β such β triplet β found " , end = ' ' ) NEW_LINE return NEW_LINE DEDENT seq = 1 NEW_LINE min_num = nums [ 0 ] NEW_LINE max_seq = - sys . maxsize - 1 NEW_LINE store_min = min_num NEW_LINE for i in range ( 1 , len ( nums ) ) : NEW_LINE INDENT if ( nums [ i ] == min_num ) : NEW_LINE continue NEW_LINE elif ( nums [ i ] < min_num ) : NEW_LINE min_num = nums [ i ] NEW_LINE continue NEW_LINE elif ( nums [ i ] < max_seq ) : NEW_LINE max_seq = nums [ i ] NEW_LINE store_min = min_num NEW_LINE elif ( nums [ i ] > max_seq ) : NEW_LINE if seq == 1 : NEW_LINE INDENT store_min = min_num NEW_LINE DEDENT seq += 1 NEW_LINE if ( seq == 3 ) : NEW_LINE INDENT print ( " Triplet : β " + str ( store_min ) + " , β " + str ( max_seq ) + " , β " + str ( nums [ i ] ) ) NEW_LINE return NEW_LINE DEDENT max_seq = nums [ i ] NEW_LINE DEDENT print ( " No β such β triplet β found " , end = ' ' ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT nums = [ 1 , 2 , - 1 , 7 , 5 ] NEW_LINE find3Numbers ( nums ) NEW_LINE DEDENT |
Maximum Product Subarray | Returns the product of max product subarray . ; Initializing result ; traversing in current subarray ; updating result every time to keep an eye over the maximum product ; updating the result for ( n - 1 ) th index . ; Driver code | def maxSubarrayProduct ( arr , n ) : NEW_LINE INDENT result = arr [ 0 ] NEW_LINE for i in range ( n ) : NEW_LINE INDENT mul = arr [ i ] NEW_LINE for j in range ( i + 1 , n ) : NEW_LINE INDENT result = max ( result , mul ) NEW_LINE mul *= arr [ j ] NEW_LINE DEDENT result = max ( result , mul ) NEW_LINE DEDENT return result NEW_LINE DEDENT arr = [ 1 , - 2 , - 3 , 0 , 7 , - 8 , - 2 ] NEW_LINE n = len ( arr ) NEW_LINE print ( " Maximum β Sub β array β product β is " , maxSubarrayProduct ( arr , n ) ) NEW_LINE |
Replace every element with the greatest element on right side | Function to replace every element with the next greatest element ; Initialize the next greatest element ; The next greatest element for the rightmost element is always - 1 ; Replace all other elements with the next greatest ; Store the current element ( needed later for updating the next greatest element ) ; Replace current element with the next greatest ; Update the greatest element , if needed ; Utility function to print an array ; Driver function to test above function | def nextGreatest ( arr ) : NEW_LINE INDENT size = len ( arr ) NEW_LINE max_from_right = arr [ size - 1 ] NEW_LINE arr [ size - 1 ] = - 1 NEW_LINE for i in range ( size - 2 , - 1 , - 1 ) : NEW_LINE INDENT temp = arr [ i ] NEW_LINE arr [ i ] = max_from_right NEW_LINE if max_from_right < temp : NEW_LINE INDENT max_from_right = temp NEW_LINE DEDENT DEDENT DEDENT def printArray ( arr ) : NEW_LINE INDENT for i in range ( 0 , len ( arr ) ) : NEW_LINE INDENT print arr [ i ] , NEW_LINE DEDENT DEDENT arr = [ 16 , 17 , 4 , 3 , 5 , 2 ] NEW_LINE nextGreatest ( arr ) NEW_LINE print " Modified β array β is " NEW_LINE printArray ( arr ) NEW_LINE |
Maximum circular subarray sum | The function returns maximum circular contiguous sum in a [ ] ; Corner Case ; Initialize sum variable which store total sum of the array . ; Initialize every variable with first value of array . ; Concept of Kadane 's Algorithm ; Kadane 's Algorithm to find Maximum subarray sum. ; Kadane 's Algorithm to find Minimum subarray sum. ; returning the maximum value ; Driver code | def maxCircularSum ( a , n ) : NEW_LINE INDENT if ( n == 1 ) : NEW_LINE INDENT return a [ 0 ] NEW_LINE DEDENT sum = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT sum += a [ i ] NEW_LINE DEDENT curr_max = a [ 0 ] NEW_LINE max_so_far = a [ 0 ] NEW_LINE curr_min = a [ 0 ] NEW_LINE min_so_far = a [ 0 ] NEW_LINE for i in range ( 1 , n ) : NEW_LINE INDENT curr_max = max ( curr_max + a [ i ] , a [ i ] ) NEW_LINE max_so_far = max ( max_so_far , curr_max ) NEW_LINE curr_min = min ( curr_min + a [ i ] , a [ i ] ) NEW_LINE min_so_far = min ( min_so_far , curr_min ) NEW_LINE DEDENT if ( min_so_far == sum ) : NEW_LINE INDENT return max_so_far NEW_LINE DEDENT return max ( max_so_far , sum - min_so_far ) NEW_LINE DEDENT a = [ 11 , 10 , - 20 , 5 , - 3 , - 5 , 8 , - 13 , 10 ] NEW_LINE n = len ( a ) NEW_LINE print ( " Maximum β circular β sum β is " , maxCircularSum ( a , n ) ) NEW_LINE |
Construction of Longest Increasing Subsequence ( N log N ) | Binary search ; Add boundary case , when array n is zero Depend on smart pointers ; Initialized with - 1 ; it will always point to empty location ; new smallest value ; arr [ i ] wants to extend largest subsequence ; arr [ i ] wants to be a potential condidate of future subsequence It will replace ceil value in tailIndices ; driver code | def GetCeilIndex ( arr , T , l , r , key ) : NEW_LINE INDENT while ( r - l > 1 ) : NEW_LINE INDENT m = l + ( r - l ) // 2 NEW_LINE if ( arr [ T [ m ] ] >= key ) : NEW_LINE INDENT r = m NEW_LINE DEDENT else : NEW_LINE INDENT l = m NEW_LINE DEDENT DEDENT return r NEW_LINE DEDENT def LongestIncreasingSubsequence ( arr , n ) : NEW_LINE INDENT tailIndices = [ 0 for i in range ( n + 1 ) ] NEW_LINE prevIndices = [ - 1 for i in range ( n + 1 ) ] NEW_LINE len = 1 NEW_LINE for i in range ( 1 , n ) : NEW_LINE INDENT if ( arr [ i ] < arr [ tailIndices [ 0 ] ] ) : NEW_LINE INDENT tailIndices [ 0 ] = i NEW_LINE DEDENT elif ( arr [ i ] > arr [ tailIndices [ len - 1 ] ] ) : NEW_LINE INDENT prevIndices [ i ] = tailIndices [ len - 1 ] NEW_LINE tailIndices [ len ] = i NEW_LINE len += 1 NEW_LINE DEDENT else : NEW_LINE INDENT pos = GetCeilIndex ( arr , tailIndices , - 1 , len - 1 , arr [ i ] ) NEW_LINE prevIndices [ i ] = tailIndices [ pos - 1 ] NEW_LINE tailIndices [ pos ] = i NEW_LINE DEDENT DEDENT print ( " LIS β of β given β input " ) NEW_LINE i = tailIndices [ len - 1 ] NEW_LINE while ( i >= 0 ) : NEW_LINE INDENT print ( arr [ i ] , " β " , end = " " ) NEW_LINE i = prevIndices [ i ] NEW_LINE DEDENT print ( ) NEW_LINE return len NEW_LINE DEDENT arr = [ 2 , 5 , 3 , 7 , 11 , 8 , 10 , 13 , 6 ] NEW_LINE n = len ( arr ) NEW_LINE print ( " LIS size " , LongestIncreasingSubsequence ( arr , n ) ) NEW_LINE |
Maximize sum of consecutive differences in a circular array | Return the maximum Sum of difference between consecutive elements ; Sorting the array ; Subtracting a1 , a2 , a3 , ... . . , a ( n / 2 ) - 1 , an / 2 twice and adding a ( n / 2 ) + 1 , a ( n / 2 ) + 2 , a ( n / 2 ) + 3 , . ... . , an - 1 , an twice . ; Driver Program | def maxSum ( arr , n ) : NEW_LINE INDENT sum = 0 NEW_LINE arr . sort ( ) NEW_LINE for i in range ( 0 , int ( n / 2 ) ) : NEW_LINE INDENT sum -= ( 2 * arr [ i ] ) NEW_LINE sum += ( 2 * arr [ n - i - 1 ] ) NEW_LINE DEDENT return sum NEW_LINE DEDENT arr = [ 4 , 2 , 1 , 8 ] NEW_LINE n = len ( arr ) NEW_LINE print ( maxSum ( arr , n ) ) NEW_LINE |
Three way partitioning of an array around a given range | Partitions arr [ 0. . n - 1 ] around [ lowVal . . highVal ] ; Initialize ext available positions for smaller ( than range ) and greater lements ; Traverse elements from left ; If current element is smaller than range , put it on next available smaller position . ; If current element is greater than range , put it on next available greater position . ; Driver code | def threeWayPartition ( arr , n , lowVal , highVal ) : NEW_LINE INDENT start = 0 NEW_LINE end = n - 1 NEW_LINE i = 0 NEW_LINE while i <= end : NEW_LINE INDENT if arr [ i ] < lowVal : NEW_LINE INDENT temp = arr [ i ] NEW_LINE arr [ i ] = arr [ start ] NEW_LINE arr [ start ] = temp NEW_LINE i += 1 NEW_LINE start += 1 NEW_LINE DEDENT elif arr [ i ] > highVal : NEW_LINE INDENT temp = arr [ i ] NEW_LINE arr [ i ] = arr [ end ] NEW_LINE arr [ end ] = temp NEW_LINE end -= 1 NEW_LINE DEDENT else : NEW_LINE INDENT i += 1 NEW_LINE DEDENT DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 1 , 14 , 5 , 20 , 4 , 2 , 54 , 20 , 87 , 98 , 3 , 1 , 32 ] NEW_LINE n = len ( arr ) NEW_LINE threeWayPartition ( arr , n , 10 , 20 ) NEW_LINE print ( " Modified β array " ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT print ( arr [ i ] , end = " β " ) NEW_LINE DEDENT DEDENT |
Generate all possible sorted arrays from alternate elements of two given sorted arrays | Function to generates and prints all sorted arrays from alternate elements of ' A [ i . . m - 1 ] ' and ' B [ j . . n - 1 ] ' If ' flag ' is true , then current element is to be included from A otherwise from B . ' len ' is the index in output array C [ ] . We print output array each time before including a character from A only if length of output array is greater than 0. We try than all possible combinations ; Include valid element from A ; Print output if there is at least one ' B ' in output array 'C ; Recur for all elements of A after current index ; this block works for the very first call to include the first element in the output array ; don 't increment lem as B is included yet ; include valid element from A and recur ; Include valid element from B and recur ; Wrapper function ; output array ; A utility function to print an array ; Driver program | def generateUtil ( A , B , C , i , j , m , n , len , flag ) : NEW_LINE INDENT if ( flag ) : NEW_LINE INDENT if ( len ) : NEW_LINE INDENT printArr ( C , len + 1 ) NEW_LINE DEDENT for k in range ( i , m ) : NEW_LINE INDENT if ( not len ) : NEW_LINE INDENT C [ len ] = A [ k ] NEW_LINE generateUtil ( A , B , C , k + 1 , j , m , n , len , not flag ) NEW_LINE DEDENT else : NEW_LINE INDENT if ( A [ k ] > C [ len ] ) : NEW_LINE INDENT C [ len + 1 ] = A [ k ] NEW_LINE generateUtil ( A , B , C , k + 1 , j , m , n , len + 1 , not flag ) NEW_LINE DEDENT DEDENT DEDENT DEDENT else : NEW_LINE INDENT for l in range ( j , n ) : NEW_LINE INDENT if ( B [ l ] > C [ len ] ) : NEW_LINE INDENT C [ len + 1 ] = B [ l ] NEW_LINE generateUtil ( A , B , C , i , l + 1 , m , n , len + 1 , not flag ) NEW_LINE DEDENT DEDENT DEDENT DEDENT def generate ( A , B , m , n ) : NEW_LINE INDENT C = [ ] NEW_LINE for i in range ( m + n + 1 ) : NEW_LINE INDENT C . append ( 0 ) NEW_LINE DEDENT generateUtil ( A , B , C , 0 , 0 , m , n , 0 , True ) NEW_LINE DEDENT def printArr ( arr , n ) : NEW_LINE INDENT for i in range ( n ) : NEW_LINE INDENT print ( arr [ i ] , " β " , end = " " ) NEW_LINE DEDENT print ( ) NEW_LINE DEDENT A = [ 10 , 15 , 25 ] NEW_LINE B = [ 5 , 20 , 30 ] NEW_LINE n = len ( A ) NEW_LINE m = len ( B ) NEW_LINE generate ( A , B , n , m ) NEW_LINE |
Minimum number of swaps required for arranging pairs adjacent to each other | This function updates indexes of elements ' a ' and 'b ; This function returns minimum number of swaps required to arrange all elements of arr [ i . . n ] become arranged ; If all pairs procesed so no swapping needed return 0 ; If current pair is valid so DO NOT DISTURB this pair and move ahead . ; Swap pair of arr [ i ] with arr [ i + 1 ] and recursively compute minimum swap required if this move is made . ; Backtrack to previous configuration . Also restore the previous indices , of one and two ; Now swap arr [ i ] with pair of arr [ i + 1 ] and recursively compute minimum swaps required for the subproblem after this move ; Backtrack to previous configuration . Also restore 3 the previous indices , of one and two ; Return minimum of two cases ; Returns minimum swaps required ; To store indices of array elements ; Store index of each element in array index ; Call the recursive function ; For simplicity , it is assumed that arr [ 0 ] is not used . The elements from index 1 to n are only valid elements ; if ( a , b ) is pair than we have assigned elements in array such that pairs [ a ] = b and pairs [ b ] = a ; Number of pairs n is half of total elements ; If there are n elements in array , then there are n pairs | def updateindex ( index , a , ai , b , bi ) : NEW_LINE INDENT index [ a ] = ai NEW_LINE index [ b ] = bi NEW_LINE DEDENT def minSwapsUtil ( arr , pairs , index , i , n ) : NEW_LINE INDENT if ( i > n ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT if ( pairs [ arr [ i ] ] == arr [ i + 1 ] ) : NEW_LINE INDENT return minSwapsUtil ( arr , pairs , index , i + 2 , n ) NEW_LINE DEDENT one = arr [ i + 1 ] NEW_LINE indextwo = i + 1 NEW_LINE indexone = index [ pairs [ arr [ i ] ] ] NEW_LINE two = arr [ index [ pairs [ arr [ i ] ] ] ] NEW_LINE arr [ i + 1 ] , arr [ indexone ] = arr [ indexone ] , arr [ i + 1 ] NEW_LINE updateindex ( index , one , indexone , two , indextwo ) NEW_LINE a = minSwapsUtil ( arr , pairs , index , i + 2 , n ) NEW_LINE arr [ i + 1 ] , arr [ indexone ] = arr [ indexone ] , arr [ i + 1 ] NEW_LINE updateindex ( index , one , indextwo , two , indexone ) NEW_LINE one = arr [ i ] NEW_LINE indexone = index [ pairs [ arr [ i + 1 ] ] ] NEW_LINE two = arr [ index [ pairs [ arr [ i + 1 ] ] ] ] NEW_LINE indextwo = i NEW_LINE arr [ i ] , arr [ indexone ] = arr [ indexone ] , arr [ i ] NEW_LINE updateindex ( index , one , indexone , two , indextwo ) NEW_LINE b = minSwapsUtil ( arr , pairs , index , i + 2 , n ) NEW_LINE arr [ i ] , arr [ indexone ] = arr [ indexone ] , arr [ i ] NEW_LINE updateindex ( index , one , indextwo , two , indexone ) NEW_LINE return 1 + min ( a , b ) NEW_LINE DEDENT def minSwaps ( n , pairs , arr ) : NEW_LINE INDENT index = [ ] NEW_LINE for i in range ( 2 * n + 1 + 1 ) : NEW_LINE INDENT index . append ( 0 ) NEW_LINE DEDENT for i in range ( 1 , 2 * n + 1 ) : NEW_LINE INDENT index [ arr [ i ] ] = i NEW_LINE DEDENT return minSwapsUtil ( arr , pairs , index , 1 , 2 * n ) NEW_LINE DEDENT arr = [ 0 , 3 , 5 , 6 , 4 , 1 , 2 ] NEW_LINE pairs = [ 0 , 3 , 6 , 1 , 5 , 4 , 2 ] NEW_LINE m = len ( pairs ) NEW_LINE n = m // 2 NEW_LINE print ( " Min β swaps β required β is β " , minSwaps ( n , pairs , arr ) ) NEW_LINE |
Replace two consecutive equal values with one greater | python program to replace two elements with equal values with one greater . ; Function to replace consecutive equal elements ; Index in result ; to print new array ; Driver Code | from __future__ import print_function NEW_LINE def replace_elements ( arr , n ) : NEW_LINE INDENT pos = 0 NEW_LINE for i in range ( 0 , n ) : NEW_LINE INDENT arr [ pos ] = arr [ i ] NEW_LINE pos = pos + 1 NEW_LINE while ( pos > 1 and arr [ pos - 2 ] == arr [ pos - 1 ] ) : NEW_LINE INDENT pos -= 1 NEW_LINE arr [ pos - 1 ] += 1 NEW_LINE DEDENT DEDENT for i in range ( 0 , pos ) : NEW_LINE INDENT print ( arr [ i ] , end = " β " ) NEW_LINE DEDENT DEDENT arr = [ 6 , 4 , 3 , 4 , 3 , 3 , 5 ] NEW_LINE n = len ( arr ) NEW_LINE replace_elements ( arr , n ) NEW_LINE |
Rearrange a binary string as alternate x and y occurrences | Function which arrange the given string ; Counting number of 0 ' s β and β 1' s in the given string . ; Printing first all 0 ' s β x - times β β and β decrement β count β of β 0' s x - times and do the similar task with '1 ; Driver code | def arrangeString ( str1 , x , y ) : NEW_LINE INDENT count_0 = 0 NEW_LINE count_1 = 0 NEW_LINE n = len ( str1 ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT if str1 [ i ] == '0' : NEW_LINE INDENT count_0 += 1 NEW_LINE DEDENT else : NEW_LINE INDENT count_1 += 1 NEW_LINE DEDENT DEDENT while count_0 > 0 or count_1 > 0 : NEW_LINE INDENT for i in range ( 0 , x ) : NEW_LINE INDENT if count_0 > 0 : NEW_LINE INDENT print ( "0" , end = " " ) NEW_LINE count_0 -= 1 NEW_LINE DEDENT DEDENT for j in range ( 0 , y ) : NEW_LINE INDENT if count_1 > 0 : NEW_LINE INDENT print ( "1" , end = " " ) NEW_LINE count_1 -= 1 NEW_LINE DEDENT DEDENT DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT str1 = "01101101101101101000000" NEW_LINE x = 1 NEW_LINE y = 2 NEW_LINE arrangeString ( str1 , x , y ) NEW_LINE DEDENT |
Shuffle 2 n integers as a1 | Python program to shuffle an array in the form of a1 , b1 , a2 , b2 , ... ; function to rearrange the array ; if size is null or odd return because it is not possible to rearrange ; start from the middle index ; each time we will set two elements from the start to the valid position by swapping ; Driver Code | arr = [ 1 , 3 , 5 , 2 , 4 , 6 ] NEW_LINE def rearrange ( n ) : NEW_LINE INDENT global arr NEW_LINE if ( n % 2 == 1 ) : NEW_LINE INDENT return NEW_LINE DEDENT currIdx = int ( ( n - 1 ) / 2 ) NEW_LINE while ( currIdx > 0 ) : NEW_LINE INDENT count = currIdx NEW_LINE swapIdx = currIdx NEW_LINE while ( count > 0 ) : NEW_LINE INDENT temp = arr [ swapIdx + 1 ] NEW_LINE arr [ swapIdx + 1 ] = arr [ swapIdx ] NEW_LINE arr [ swapIdx ] = temp NEW_LINE swapIdx = swapIdx + 1 NEW_LINE count = count - 1 NEW_LINE DEDENT currIdx = currIdx - 1 NEW_LINE DEDENT DEDENT n = len ( arr ) NEW_LINE rearrange ( n ) NEW_LINE for i in range ( 0 , n ) : NEW_LINE INDENT print ( " { } β " . format ( arr [ i ] ) , end = " " ) NEW_LINE DEDENT |
Maximum difference between two elements such that larger element appears after the smaller number | The function assumes that there are at least two elements in array . The function returns a negative value if the array is sorted in decreasing order . Returns 0 if elements are equal ; Driver program to test above function ; Function calling | def maxDiff ( arr , arr_size ) : NEW_LINE INDENT max_diff = arr [ 1 ] - arr [ 0 ] NEW_LINE for i in range ( 0 , arr_size ) : NEW_LINE INDENT for j in range ( i + 1 , arr_size ) : NEW_LINE INDENT if ( arr [ j ] - arr [ i ] > max_diff ) : NEW_LINE INDENT max_diff = arr [ j ] - arr [ i ] NEW_LINE DEDENT DEDENT DEDENT return max_diff NEW_LINE DEDENT arr = [ 1 , 2 , 90 , 10 , 110 ] NEW_LINE size = len ( arr ) NEW_LINE print ( " Maximum β difference β is " , maxDiff ( arr , size ) ) NEW_LINE |
Maximum difference between two elements such that larger element appears after the smaller number | The function assumes that there are at least two elements in array . The function returns a negative value if the array is sorted in decreasing order and returns 0 if elements are equal ; Initialize Result ; Initialize max element from right side ; Driver Code ; Function calling | def maxDiff ( arr , n ) : NEW_LINE INDENT maxDiff = - 1 NEW_LINE maxRight = arr [ n - 1 ] NEW_LINE for i in range ( n - 2 , - 1 , - 1 ) : NEW_LINE INDENT if ( arr [ i ] > maxRight ) : NEW_LINE INDENT maxRight = arr [ i ] NEW_LINE DEDENT else : NEW_LINE INDENT diff = maxRight - arr [ i ] NEW_LINE if ( diff > maxDiff ) : NEW_LINE INDENT maxDiff = diff NEW_LINE DEDENT DEDENT DEDENT return maxDiff NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 1 , 2 , 90 , 10 , 110 ] NEW_LINE n = len ( arr ) NEW_LINE print ( " Maximum β difference β is " , maxDiff ( arr , n ) ) NEW_LINE DEDENT |
Maximum difference between two elements such that larger element appears after the smaller number | The function assumes that there are at least two elements in array . The function returns a negative value if the array is sorted in decreasing order and returns 0 if elements are equal ; Initialize diff , current sum and max sum ; Calculate current diff ; Calculate current sum ; Update max sum , if needed ; Driver Code ; Function calling | def maxDiff ( arr , n ) : NEW_LINE INDENT diff = arr [ 1 ] - arr [ 0 ] NEW_LINE curr_sum = diff NEW_LINE max_sum = curr_sum NEW_LINE for i in range ( 1 , n - 1 ) : NEW_LINE INDENT diff = arr [ i + 1 ] - arr [ i ] NEW_LINE if ( curr_sum > 0 ) : NEW_LINE INDENT curr_sum += diff NEW_LINE DEDENT else : NEW_LINE INDENT curr_sum = diff NEW_LINE DEDENT if ( curr_sum > max_sum ) : NEW_LINE INDENT max_sum = curr_sum NEW_LINE DEDENT DEDENT return max_sum NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 80 , 2 , 6 , 3 , 100 ] NEW_LINE n = len ( arr ) NEW_LINE print ( " Maximum β difference β is " , maxDiff ( arr , n ) ) NEW_LINE DEDENT |
Find the maximum element in an array which is first increasing and then decreasing | Python3 program to find maximum element ; Driver program to check above functions | def findMaximum ( arr , low , high ) : NEW_LINE INDENT max = arr [ low ] NEW_LINE i = low NEW_LINE for i in range ( high + 1 ) : NEW_LINE INDENT if arr [ i ] > max : NEW_LINE INDENT max = arr [ i ] NEW_LINE DEDENT DEDENT return max NEW_LINE DEDENT arr = [ 1 , 30 , 40 , 50 , 60 , 70 , 23 , 20 ] NEW_LINE n = len ( arr ) NEW_LINE print ( " The β maximum β element β is β % d " % findMaximum ( arr , 0 , n - 1 ) ) NEW_LINE |
Subsets and Splits