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 u... | 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... |
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 ch... | 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 = [ ... |
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 fo... | 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 max... |
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 w... | 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 g... |
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... | 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 = m... |
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 [ ... |
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 be... | 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 - p... |
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 valu... | 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 (... |
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... | 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_... |
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... |
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 DEDE... |
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 ... |
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 ) ; ... | 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 ( p... |
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 f... | 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 ] == ... |
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 progra... | 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_... |
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 [ ] ... | 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 ... |
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 ... | 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 ) : N... |
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... | 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... |
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 ... | 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 (... |
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... |
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... | 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 = binomialCoeffic... |
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 1... | 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 remaind... | 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 ... |
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 + ... |
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 Cod... | 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... |
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 ... |
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 I... |
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 (... | 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 ) * ( y... |
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... | 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 fo... |
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 ) NE... |
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[].... | 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... |
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 ) : N... |
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... |
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 chan... | 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_LIN... |
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 coun... | 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 ... |
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 ; NE... |
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 ; ... | 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_L... |
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... | 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 ... |
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 ... |
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 β ... |
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 β num... |
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 ]... |
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 p... | 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 ( ri... |
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 I... |
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 DEDE... |
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 , " i... |
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 __na... |
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 ... |
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_LI... |
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... |
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... |
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 &... | 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... |
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... |
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_LIN... |
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 ) ... |
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 _ _ " : NE... |
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 ( ... |
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_... |
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 i... | 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_LI... |
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... |
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... | 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 , backsla... |
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 ... | 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_LI... |
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 ... | 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... |
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 ; ... | 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 f... |
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... | 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... |
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... |
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 ] ... | 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 rang... |
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 res... |
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 ( ne... | 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_ri... |
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... | 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 i... |
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 condidat... | 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... |
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 . ; Drive... | 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 ... |
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 .... | 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... |
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 ind... | 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 ... |
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 p... | 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 minSwap... |
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... |
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 ... |
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 swap... | 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_LIN... |
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 funct... | 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 retu... |
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 m... | 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 ) :... |
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 an... | 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... |
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 ) ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.