text
stringlengths 17
3.65k
| code
stringlengths 70
5.84k
|
---|---|
Find the smallest positive number which can not be represented by given digits | Function to find the smallest positive number which can not be represented by given digits ; Storing the count of 0 digit or store the value at 0 th index ; Calculates the min value in the array starting from 1 st index and also store its index . ; If its value at 0 th index is less than min value than either 10 , 100 , 1000 ... can 't be expressed ; If its value is greater than min value then iterate the loop upto first min value index and simply print its index value . ; Driver code ; Value of N is always 10 as we take digit from 0 to 9 ; Calling function | def expressDigit ( arr , n ) : NEW_LINE INDENT min = 9 NEW_LINE index = 0 NEW_LINE temp = 0 NEW_LINE temp = arr [ 0 ] NEW_LINE for i in range ( 1 , 10 ) : NEW_LINE INDENT if ( arr [ i ] < min ) : NEW_LINE INDENT min = arr [ i ] NEW_LINE index = i NEW_LINE DEDENT DEDENT if ( temp < min ) : NEW_LINE INDENT print ( 1 , end = " " ) NEW_LINE for i in range ( 1 , temp + 1 ) : NEW_LINE INDENT print ( 0 , end = " " ) NEW_LINE DEDENT DEDENT else : NEW_LINE INDENT for i in range ( min ) : NEW_LINE INDENT print ( index , end = " " ) NEW_LINE DEDENT print ( index ) NEW_LINE DEDENT DEDENT arr = [ 2 , 2 , 1 , 2 , 1 , 1 , 3 , 1 , 1 , 1 ] NEW_LINE N = 10 NEW_LINE expressDigit ( arr , N ) NEW_LINE |
Find the average of k digits from the beginning and l digits from the end of the given number | implementation of the approach ; Function to return the count of digits in num ; Function to return the sum of first n digits of num ; Remove the unnecessary digits ; Function to return the sum of the last n digits of num ; If the average can 't be calculated without using the same digit more than once ; Sum of the last l digits of n ; Sum of the first k digits of n ( totalDigits - k ) must be removed from the end of the number to get the remaining k digits from the beginning ; Return the average ; Driver code | from math import pow NEW_LINE def countDigits ( num ) : NEW_LINE INDENT cnt = 0 NEW_LINE while ( num > 0 ) : NEW_LINE INDENT cnt += 1 NEW_LINE num //= 10 NEW_LINE DEDENT return cnt NEW_LINE DEDENT def sumFromStart ( num , n , rem ) : NEW_LINE INDENT num //= pow ( 10 , rem ) NEW_LINE sum = 0 NEW_LINE while ( num > 0 ) : NEW_LINE INDENT sum += ( num % 10 ) NEW_LINE num //= 10 NEW_LINE DEDENT return sum NEW_LINE DEDENT def sumFromEnd ( num , n ) : NEW_LINE INDENT sum = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT sum += ( num % 10 ) NEW_LINE num //= 10 NEW_LINE DEDENT return sum NEW_LINE DEDENT def getAverage ( n , k , l ) : NEW_LINE INDENT totalDigits = countDigits ( n ) NEW_LINE if ( totalDigits < ( k + l ) ) : NEW_LINE INDENT return - 1 NEW_LINE DEDENT sum1 = sumFromEnd ( n , l ) NEW_LINE sum2 = sumFromStart ( n , k , totalDigits - k ) NEW_LINE return ( sum1 + sum2 ) / ( k + l ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT n = 123456 NEW_LINE k = 2 NEW_LINE l = 3 NEW_LINE print ( getAverage ( n , k , l ) ) NEW_LINE DEDENT |
Print N terms of Withoff Sequence | Python3 program to find Wythoff array ; Function to find the n , k term of Wythoff array ; tau = ( sqrt ( 5 ) + 1 ) / 2 ; Already_stored ; T ( n , - 1 ) = n - 1. ; T ( n , 0 ) = floor ( n * tau ) . ; T ( n , k ) = T ( n , k - 1 ) + T ( n , k - 2 ) for k >= 1. ; Store ; Return the ans ; Function to find first n terms of Wythoff array by traversing in anti - diagonal ; Map to store the Wythoff array ; Anti diagonal ; Driver code ; Function call | import math NEW_LINE def Wythoff ( mp , n , k ) : NEW_LINE INDENT tau = ( math . sqrt ( 5 ) + 1 ) / 2 NEW_LINE t_n_k = 0 NEW_LINE if ( ( n in mp ) and ( k in mp [ n ] ) ) : NEW_LINE INDENT return mp [ n ] [ k ] ; NEW_LINE DEDENT if ( k == - 1 ) : NEW_LINE INDENT return n - 1 ; NEW_LINE DEDENT elif ( k == 0 ) : NEW_LINE INDENT t_n_k = math . floor ( n * tau ) ; NEW_LINE DEDENT else : NEW_LINE INDENT t_n_k = Wythoff ( mp , n , k - 1 ) + Wythoff ( mp , n , k - 2 ) NEW_LINE DEDENT if n not in mp : NEW_LINE INDENT mp [ n ] = dict ( ) NEW_LINE DEDENT mp [ n ] [ k ] = t_n_k ; NEW_LINE return int ( t_n_k ) NEW_LINE DEDENT def Wythoff_Array ( n ) : NEW_LINE INDENT i = 0 NEW_LINE j = 0 NEW_LINE count = 0 ; NEW_LINE mp = dict ( ) NEW_LINE while ( count < n ) : NEW_LINE INDENT print ( Wythoff ( mp , i + 1 , j + 1 ) , end = ' ' ) NEW_LINE count += 1 NEW_LINE if ( count != n ) : NEW_LINE INDENT print ( " , β " , end = ' ' ) NEW_LINE DEDENT i += 1 NEW_LINE j -= 1 NEW_LINE if ( j < 0 ) : NEW_LINE INDENT j = i ; NEW_LINE i = 0 ; NEW_LINE DEDENT DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT n = 15 ; NEW_LINE Wythoff_Array ( n ) ; NEW_LINE DEDENT |
Sum of two numbers if the original ratio and new ratio obtained by adding a given number to each number is given | Function to return the sum of numbers which are in the ration a : b and after adding x to both the numbers the new ratio becomes c : d ; Driver code | def sum ( a , b , c , d , x ) : NEW_LINE INDENT ans = ( ( x * ( a + b ) * ( c - d ) ) / ( ( a * d ) - ( b * c ) ) ) ; NEW_LINE return ans ; NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT a , b , c , d , x = 1 , 2 , 9 , 13 , 5 ; NEW_LINE print ( sum ( a , b , c , d , x ) ) ; NEW_LINE DEDENT |
Triangle of numbers arising from Gilbreath 's conjecture | Python3 code for printing the Triangle of numbers arising from Gilbreath 's conjecture ; Check whether the number is prime or not ; Set the 0 th row of the matrix with c primes from 0 , 0 to 0 , c - 1 ; Find the n , k term of matrix of Gilbreath 's conjecture ; recursively find ; store the ans ; Print first n terms of Gilbreath sequence successive absolute differences of primes read by antidiagonals upwards . ; map to store the matrix and hash to check if the element is present or not ; set the primes of first row ; print the Gilbreath number ; increase the count ; anti diagonal upwards ; Driver code | import math NEW_LINE def is_Prime ( n ) : NEW_LINE INDENT if ( n < 2 ) : NEW_LINE INDENT return False ; NEW_LINE DEDENT for i in range ( 2 , int ( math . sqrt ( n ) ) + 1 ) : NEW_LINE INDENT if ( n % i == 0 ) : NEW_LINE INDENT return False ; NEW_LINE DEDENT DEDENT return True ; NEW_LINE DEDENT def set_primes ( mp , hash , c ) : NEW_LINE INDENT count = 0 ; NEW_LINE i = 2 NEW_LINE while ( count < c ) : NEW_LINE INDENT if ( is_Prime ( i ) ) : NEW_LINE INDENT if 0 not in mp : NEW_LINE INDENT mp [ 0 ] = dict ( ) NEW_LINE DEDENT mp [ 0 ] [ count ] = i ; NEW_LINE count += 1 NEW_LINE if 0 not in hash : NEW_LINE INDENT hash [ 0 ] = dict ( ) NEW_LINE DEDENT hash [ 0 ] [ count - 1 ] = 1 ; NEW_LINE DEDENT i += 1 NEW_LINE DEDENT DEDENT def Gilbreath ( mp , hash , n , k ) : NEW_LINE INDENT if ( n in hash and k in hash [ n ] and hash [ n ] [ k ] != 0 ) : NEW_LINE INDENT return mp [ n ] [ k ] ; NEW_LINE DEDENT ans = abs ( Gilbreath ( mp , hash , n - 1 , k + 1 ) - Gilbreath ( mp , hash , n - 1 , k ) ) ; NEW_LINE if n not in mp : NEW_LINE INDENT mp [ n ] = dict ( ) NEW_LINE DEDENT mp [ n ] [ k ] = ans ; NEW_LINE return ans ; NEW_LINE DEDENT def solve ( n ) : NEW_LINE INDENT i = 0 NEW_LINE j = 0 NEW_LINE count = 0 ; NEW_LINE mp = dict ( ) NEW_LINE hash = dict ( ) NEW_LINE set_primes ( mp , hash , 100 ) ; NEW_LINE while ( count < n ) : NEW_LINE INDENT print ( Gilbreath ( mp , hash , i , j ) , end = ' , β ' ) NEW_LINE count += 1 NEW_LINE i -= 1 NEW_LINE j += 1 NEW_LINE if ( i < 0 ) : NEW_LINE INDENT i = j ; NEW_LINE j = 0 ; NEW_LINE DEDENT DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT n = 15 ; NEW_LINE solve ( n ) ; NEW_LINE DEDENT |
Roots of the quadratic equation when a + b + c = 0 without using Shridharacharya formula | Function to print the roots of the quadratic equation when a + b + c = 0 ; Driver code | def printRoots ( a , b , c ) : NEW_LINE INDENT print ( 1 , " , " , c / ( a * 1.0 ) ) NEW_LINE DEDENT a = 2 NEW_LINE b = 3 NEW_LINE c = - 5 NEW_LINE printRoots ( a , b , c ) NEW_LINE |
Longest alternative parity subsequence | Function to find the longest ; Marks the starting of odd number as sequence and alternatively changes ; Finding the longest odd / even sequence ; Find odd number ; Find even number ; Length of the longest even / odd sequence ; Find odd number ; Find even number ; Answer is maximum of both odd / even or even / odd subsequence ; Driver Code | def longestAlternativeSequence ( a , n ) : NEW_LINE INDENT maxi1 = 0 NEW_LINE f1 = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( f1 == 0 ) : NEW_LINE INDENT if ( a [ i ] % 2 ) : NEW_LINE INDENT f1 = 1 NEW_LINE maxi1 += 1 NEW_LINE DEDENT DEDENT else : NEW_LINE INDENT if ( a [ i ] % 2 == 0 ) : NEW_LINE INDENT maxi1 += 1 NEW_LINE f1 = 0 NEW_LINE DEDENT DEDENT DEDENT maxi2 = 0 NEW_LINE f2 = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( f2 ) : NEW_LINE INDENT if ( a [ i ] % 2 ) : NEW_LINE INDENT f2 = 1 NEW_LINE maxi2 += 1 NEW_LINE DEDENT DEDENT else : NEW_LINE INDENT if ( a [ i ] % 2 == 0 ) : NEW_LINE INDENT maxi2 += 1 NEW_LINE f2 = 0 NEW_LINE DEDENT DEDENT DEDENT return max ( maxi1 , maxi2 ) NEW_LINE DEDENT a = [ 13 , 16 , 8 , 9 , 32 , 10 ] NEW_LINE n = len ( a ) NEW_LINE print ( longestAlternativeSequence ( a , n ) ) NEW_LINE |
Nambiar Number Generator | Function to return the Nambiar number of the given number ; If there is no digit to choose ; Choose the first digit ; Chosen digit 's parity ; To store the sum of the consecutive digits starting from the chosen digit ; While there are digits to choose ; Update the sum ; If the parity differs ; Return the current sum concatenated with the Numbiar number for the rest of the String ; Driver code | def nambiarNumber ( Str , i ) : NEW_LINE INDENT if ( i >= len ( Str ) ) : NEW_LINE INDENT return " " NEW_LINE DEDENT firstDigit = ord ( Str [ i ] ) - ord ( '0' ) NEW_LINE digitParity = firstDigit % 2 NEW_LINE sumDigits = 0 NEW_LINE while ( i < len ( Str ) ) : NEW_LINE INDENT sumDigits += ( ord ( Str [ i ] ) - ord ( '0' ) ) NEW_LINE sumParity = sumDigits % 2 NEW_LINE if ( digitParity != sumParity ) : NEW_LINE INDENT break NEW_LINE DEDENT i += 1 NEW_LINE DEDENT return ( " " + str ( sumDigits ) + nambiarNumber ( Str , i + 1 ) ) NEW_LINE DEDENT Str = "9880127431" NEW_LINE print ( nambiarNumber ( Str , 0 ) ) NEW_LINE |
Program to find the Depreciation of Value | Python 3 program to find depreciation of the value initial value , rate and time are given ; Function to return the depreciation of value ; Driver Code | from math import pow NEW_LINE def Depreciation ( v , r , t ) : NEW_LINE INDENT D = v * pow ( ( 1 - r / 100 ) , t ) NEW_LINE return D NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT V1 = 200 NEW_LINE R = 10 NEW_LINE T = 2 NEW_LINE print ( int ( Depreciation ( V1 , R , T ) ) ) NEW_LINE DEDENT |
Program to find first N Fermat Numbers | Iterative Function to calculate ( x ^ y ) in O ( log y ) ; res = 1 Initialize result ; If y is odd , multiply x with the result ; n must be even now y = y >> 1 y = y / 2 x = x * x Change x to x ^ 2 ; Function to find nth fermat number ; 2 to the power i ; 2 to the power 2 ^ i ; Function to find first n Fermat numbers ; Calculate 2 ^ 2 ^ i ; Driver code ; Function call | def power ( x , y ) : NEW_LINE INDENT while ( y > 0 ) : NEW_LINE INDENT if ( y & 1 ) : NEW_LINE INDENT res = res * x NEW_LINE DEDENT DEDENT return res NEW_LINE DEDENT def Fermat ( i ) : NEW_LINE INDENT power2_i = power ( 2 , i ) NEW_LINE power2_2_i = power ( 2 , power2_i ) NEW_LINE return power2_2_i + 1 NEW_LINE DEDENT def Fermat_Number ( n ) : NEW_LINE INDENT for i in range ( n ) : NEW_LINE INDENT print ( Fermat ( i ) , end = " " ) NEW_LINE if ( i != n - 1 ) : NEW_LINE INDENT print ( end = " , β " ) NEW_LINE DEDENT DEDENT DEDENT n = 7 NEW_LINE Fermat_Number ( n ) NEW_LINE |
Highly Totient Number | Function to find euler totient number ; Consider all prime factors of n and subtract their multiples from result ; Check if p is a prime factor . ; If yes , then update n and result ; If n has a prime factor greater than sqrt ( n ) ( There can be at - most one such prime factor ) ; Function to find first n highly totient numbers ; Count of Highly totient numbers and value of count of phi of previous numbers ; Store all the values of phi ( x ) upto 10 ^ 5 with frequencies ; If count is greater than count of previous element ; Display the number ; Store the value of phi ; Driver code ; Function call | def phi ( n ) : NEW_LINE INDENT p = 2 NEW_LINE while ( p * p <= n ) : NEW_LINE INDENT if ( n % p == 0 ) : NEW_LINE INDENT while ( n % p == 0 ) : NEW_LINE INDENT n //= p ; NEW_LINE DEDENT result -= ( result // p ) ; NEW_LINE DEDENT p += 1 NEW_LINE DEDENT if ( n > 1 ) : NEW_LINE INDENT result -= ( result // n ) ; NEW_LINE DEDENT return result ; NEW_LINE DEDENT def Highly_Totient ( n ) : NEW_LINE INDENT count = 0 NEW_LINE p_count = - 1 NEW_LINE mp = dict ( ) NEW_LINE i = 1 NEW_LINE while i < 100000 : NEW_LINE INDENT tmp = phi ( i ) NEW_LINE if tmp not in mp : NEW_LINE INDENT mp [ tmp ] = 0 NEW_LINE DEDENT mp [ tmp ] += 1 ; NEW_LINE i += 1 NEW_LINE DEDENT i = 1 NEW_LINE while ( count < n ) : NEW_LINE INDENT if ( ( i in mp ) and mp [ i ] > p_count ) : NEW_LINE INDENT print ( i , end = ' ' ) ; NEW_LINE if ( count < n - 1 ) : NEW_LINE INDENT print ( " , β " , end = ' ' ) ; NEW_LINE DEDENT p_count = mp [ i ] ; NEW_LINE count += 1 NEW_LINE DEDENT i += 1 NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT n = 20 ; NEW_LINE Highly_Totient ( n ) ; NEW_LINE DEDENT |
Program to find the Speed of train as per speed of sound | Python3 implementation of the approach ; Function to find the Speed of train ; Driver code ; calling Function | from math import ceil NEW_LINE def speedOfTrain ( X , Y ) : NEW_LINE INDENT Speed = 0 NEW_LINE Speed = 1188 * ( ( X - Y ) / Y ) NEW_LINE return Speed NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT X = 8 NEW_LINE Y = 7.2 NEW_LINE print ( ceil ( speedOfTrain ( X , Y ) ) , end = " β km / hr " ) NEW_LINE DEDENT |
Maximum value of division of two numbers in an Array | Function to maximum value of division of two numbers in an array ; Traverse through the array ; Return the required answer ; Driver code | def Division ( a , n ) : NEW_LINE INDENT maxi = - 10 ** 9 NEW_LINE mini = 10 ** 9 NEW_LINE for i in a : NEW_LINE INDENT maxi = max ( i , maxi ) NEW_LINE mini = min ( i , mini ) NEW_LINE DEDENT return maxi // mini NEW_LINE DEDENT a = [ 3 , 7 , 9 , 3 , 11 ] NEW_LINE n = len ( a ) NEW_LINE print ( Division ( a , n ) ) NEW_LINE |
Ramanujan Prime | Python3 program to find Ramanujan numbers ; FUnction to return a vector of primes ; Create a boolean array " prime [ 0 . . n ] " and initialize all entries it as true . A value in prime [ i ] will finally be false if i is Not a prime , else true . ; If prime [ p ] is not changed , then it is a prime ; Update all multiples of p greater than or equal to the square of it . numbers which are multiple of p and are less than p ^ 2 are already been marked . ; Print all prime numbers ; Function to find number of primes less than or equal to x ; Binary search to find out number of primes less than or equal to x ; Function to find the nth ramanujan prime ; For n >= 1 , a ( n ) < 4 * n * log ( 4 n ) ; We start from upperbound and find where pi ( i ) - pi ( i / 2 ) < n the previous number being the nth ramanujan prime ; Function to find first n Ramanujan numbers ; Get the prime numbers ; Driver code | from math import log , ceil NEW_LINE MAX = 1000000 NEW_LINE def addPrimes ( ) : NEW_LINE INDENT n = MAX NEW_LINE prime = [ True for i in range ( n + 1 ) ] NEW_LINE for p in range ( 2 , n + 1 ) : NEW_LINE INDENT if p * p > n : NEW_LINE INDENT break NEW_LINE DEDENT if ( prime [ p ] == True ) : NEW_LINE INDENT for i in range ( 2 * p , n + 1 , p ) : NEW_LINE INDENT prime [ i ] = False NEW_LINE DEDENT DEDENT DEDENT ans = [ ] NEW_LINE for p in range ( 2 , n + 1 ) : NEW_LINE INDENT if ( prime [ p ] ) : NEW_LINE INDENT ans . append ( p ) NEW_LINE DEDENT DEDENT return ans NEW_LINE DEDENT def pi ( x , v ) : NEW_LINE INDENT l , r = 0 , len ( v ) - 1 NEW_LINE m , i = 0 , - 1 NEW_LINE while ( l <= r ) : NEW_LINE INDENT m = ( l + r ) // 2 NEW_LINE if ( v [ m ] <= x ) : NEW_LINE INDENT i = m NEW_LINE l = m + 1 NEW_LINE DEDENT else : NEW_LINE INDENT r = m - 1 NEW_LINE DEDENT DEDENT return i + 1 NEW_LINE DEDENT def Ramanujan ( n , v ) : NEW_LINE INDENT upperbound = ceil ( 4 * n * ( log ( 4 * n ) / log ( 2 ) ) ) NEW_LINE for i in range ( upperbound , - 1 , - 1 ) : NEW_LINE INDENT if ( pi ( i , v ) - pi ( i / 2 , v ) < n ) : NEW_LINE INDENT return 1 + i NEW_LINE DEDENT DEDENT DEDENT def Ramanujan_Numbers ( n ) : NEW_LINE INDENT c = 1 NEW_LINE v = addPrimes ( ) NEW_LINE for i in range ( 1 , n + 1 ) : NEW_LINE INDENT print ( Ramanujan ( i , v ) , end = " " ) NEW_LINE if ( i != n ) : NEW_LINE INDENT print ( end = " , β " ) NEW_LINE DEDENT DEDENT DEDENT n = 10 NEW_LINE Ramanujan_Numbers ( n ) NEW_LINE |
Quadruplet pair with XOR zero in the given Array | Python3 implementation of the approach ; Function that returns true if the array contains a valid quadruplet pair ; We can always find a valid quadruplet pair for array size greater than MAX ; For smaller size arrays , perform brute force ; Driver code | MAX = 130 NEW_LINE def validQuadruple ( arr , n ) : NEW_LINE INDENT if ( n >= MAX ) : NEW_LINE INDENT return True NEW_LINE DEDENT for i in range ( n ) : NEW_LINE INDENT for j in range ( i + 1 , n ) : NEW_LINE INDENT for k in range ( j + 1 , n ) : NEW_LINE INDENT for l in range ( k + 1 , n ) : NEW_LINE INDENT if ( ( arr [ i ] ^ arr [ j ] ^ arr [ k ] ^ arr [ l ] ) == 0 ) : NEW_LINE INDENT return True NEW_LINE DEDENT DEDENT DEDENT DEDENT DEDENT return False NEW_LINE DEDENT arr = [ 1 , 0 , 2 , 3 , 7 ] NEW_LINE n = len ( arr ) NEW_LINE if ( validQuadruple ( arr , n ) ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT |
Find the number of words of X vowels and Y consonants that can be formed from M vowels and N consonants | Function to returns factorial of n ; Function to find nCr ; Function to find the number of words of X vowels and Y consonants can be formed from M vowels and N consonants ; Driver code ; Function call | def fact ( n ) : NEW_LINE INDENT res = 1 NEW_LINE for i in range ( 2 , n + 1 , 1 ) : NEW_LINE INDENT res = res * i NEW_LINE DEDENT return res NEW_LINE DEDENT def nCr ( n , r ) : NEW_LINE INDENT return fact ( n ) // ( fact ( r ) * fact ( n - r ) ) NEW_LINE DEDENT def NumberOfWays ( X , Y , M , N ) : NEW_LINE INDENT return fact ( X + Y ) * nCr ( M , X ) * nCr ( N , Y ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT X = 2 NEW_LINE Y = 2 NEW_LINE M = 3 NEW_LINE N = 3 NEW_LINE print ( NumberOfWays ( X , Y , M , N ) ) NEW_LINE DEDENT |
Program for sum of cosh ( x ) series upto Nth term | function to return the factorial of a number ; function to return the Sum of the series ; Driver code | def fact ( n ) : NEW_LINE INDENT i , fac = 1 , 1 NEW_LINE for i in range ( 1 , n + 1 ) : NEW_LINE INDENT fac = fac * i NEW_LINE DEDENT return fac NEW_LINE DEDENT def log_Expansion ( x , n ) : NEW_LINE INDENT Sum = 0 NEW_LINE i = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT Sum = Sum + pow ( x , 2 * i ) / fact ( 2 * i ) NEW_LINE DEDENT return Sum NEW_LINE DEDENT x = 1 NEW_LINE n = 10 NEW_LINE print ( log_Expansion ( x , n ) ) NEW_LINE |
Find prime numbers in the first half and second half of an array | Function to check if a number is prime or not ; Function to find whether elements are prime or not ; Traverse in the given range ; Check if a number is prime or not ; Function to print the prime numbers in the first half and second half of an array ; Driver Code ; Function call | def prime ( n ) : NEW_LINE INDENT for i in range ( 2 , n ) : NEW_LINE INDENT if i * i > n : NEW_LINE INDENT break NEW_LINE DEDENT if ( n % i == 0 ) : NEW_LINE INDENT return False ; NEW_LINE DEDENT DEDENT return True NEW_LINE DEDENT def prime_range ( start , end , a ) : NEW_LINE INDENT for i in range ( start , end ) : NEW_LINE INDENT if ( prime ( a [ i ] ) ) : NEW_LINE INDENT print ( a [ i ] , end = " β " ) NEW_LINE DEDENT DEDENT DEDENT def Print ( arr , n ) : NEW_LINE INDENT print ( " Prime β numbers β in β the " , " first β half β are β " , end = " " ) NEW_LINE prime_range ( 0 , n // 2 , arr ) NEW_LINE print ( ) NEW_LINE print ( " Prime β numbers β in β the " , " second β half β are β " , end = " " ) NEW_LINE prime_range ( n // 2 , n , arr ) NEW_LINE print ( ) NEW_LINE DEDENT arr = [ 2 , 5 , 10 , 15 , 17 , 21 , 23 ] NEW_LINE n = len ( arr ) NEW_LINE Print ( arr , n ) NEW_LINE |
Count of elements that can be deleted without disturbing the mean of the initial array | Function to find the elements which do not change the mean on removal ; To store the Sum of the array elements ; To store the initial mean ; to store the count of required elements ; Iterate over the array ; Finding the new mean ; If the new mean equals to the initial mean ; Driver code | def countElements ( arr , n ) : NEW_LINE INDENT Sum = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT Sum += arr [ i ] NEW_LINE DEDENT mean = Sum / n NEW_LINE cnt = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT newMean = ( Sum - arr [ i ] ) / ( n - 1 ) NEW_LINE if ( newMean == mean ) : NEW_LINE INDENT cnt += 1 NEW_LINE DEDENT DEDENT return cnt NEW_LINE DEDENT arr = [ 1 , 2 , 3 , 4 , 5 ] NEW_LINE n = len ( arr ) NEW_LINE print ( countElements ( arr , n ) ) NEW_LINE |
Find maximum xor of k elements in an array | Python implementation of the approach ; Function to return the maximum xor for a subset of size j from the given array ; If the subset is complete then return the xor value of the selected elements ; Return if already calculated for some mask and j at the i 'th index ; Initialize answer to 0 ; If we can still include elements in our subset include the i 'th element ; Exclude the i 'th element ans store the max of both operations ; Driver code | MAX = 10000 NEW_LINE MAX_ELEMENT = 50 NEW_LINE dp = [ [ [ - 1 for i in range ( MAX ) ] for j in range ( MAX_ELEMENT ) ] for k in range ( MAX_ELEMENT ) ] NEW_LINE def Max_Xor ( arr , i , j , mask , n ) : NEW_LINE INDENT if ( i >= n ) : NEW_LINE INDENT if ( j == 0 ) : NEW_LINE INDENT return mask NEW_LINE DEDENT else : NEW_LINE INDENT return 0 NEW_LINE DEDENT DEDENT if ( dp [ i ] [ j ] [ mask ] != - 1 ) : NEW_LINE INDENT return dp [ i ] [ j ] [ mask ] NEW_LINE DEDENT ans = 0 NEW_LINE if ( j > 0 ) : NEW_LINE INDENT ans = Max_Xor ( arr , i + 1 , j - 1 , mask ^ arr [ i ] , n ) NEW_LINE DEDENT ans = max ( ans , Max_Xor ( arr , i + 1 , j , mask , n ) ) NEW_LINE dp [ i ] [ j ] [ mask ] = ans NEW_LINE return ans NEW_LINE DEDENT arr = [ 2 , 5 , 4 , 1 , 3 , 7 , 6 , 8 ] NEW_LINE n = len ( arr ) NEW_LINE k = 3 NEW_LINE print ( Max_Xor ( arr , 0 , k , 0 , n ) ) NEW_LINE |
Find the prime P using given four integers | Python3 program to possible prime number ; Function to check if a number is prime or not ; Function to find possible prime number ; Find a possible prime number ; Last condition ; Driver code ; Function call | from math import sqrt NEW_LINE def Prime ( n ) : NEW_LINE INDENT for j in range ( 2 , int ( sqrt ( n ) ) + 1 , 1 ) : NEW_LINE INDENT if ( n % j == 0 ) : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT return True NEW_LINE DEDENT def find_prime ( x , xsqmodp , y , ysqmodp ) : NEW_LINE INDENT n = x * x - xsqmodp NEW_LINE n1 = y * y - ysqmodp NEW_LINE for j in range ( 2 , max ( int ( sqrt ( n ) ) , int ( sqrt ( n1 ) ) ) , 1 ) : NEW_LINE INDENT if ( n % j == 0 and ( x * x ) % j == xsqmodp and n1 % j == 0 and ( y * y ) % j == ysqmodp ) : NEW_LINE INDENT if ( Prime ( j ) ) : NEW_LINE INDENT return j NEW_LINE DEDENT DEDENT j1 = n // j NEW_LINE if ( n % j1 == 0 and ( x * x ) % j1 == xsqmodp and n1 % j1 == 0 and ( y * y ) % j1 == ysqmodp ) : NEW_LINE INDENT if ( Prime ( j1 ) ) : NEW_LINE INDENT return j1 NEW_LINE DEDENT DEDENT j1 = n1 // j NEW_LINE if ( n % j1 == 0 and ( x * x ) % j1 == xsqmodp and n1 % j1 == 0 and ( y * y ) % j1 == ysqmodp ) : NEW_LINE INDENT if ( Prime ( j1 ) ) : NEW_LINE INDENT return j1 NEW_LINE DEDENT DEDENT DEDENT if ( n == n1 ) : NEW_LINE INDENT return n NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT x = 3 NEW_LINE xsqmodp = 0 NEW_LINE y = 5 NEW_LINE ysqmodp = 1 NEW_LINE print ( find_prime ( x , xsqmodp , y , ysqmodp ) ) NEW_LINE DEDENT |
Time taken per hour for stoppage of Car | Python3 implementation of the approach ; Function to return the time taken per hour for stoppage ; Driver code | import math NEW_LINE def numberOfMinutes ( S , S1 ) : NEW_LINE INDENT Min = 0 ; NEW_LINE Min = ( ( S - S1 ) / math . floor ( S ) ) * 60 ; NEW_LINE return int ( Min ) ; NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT S , S1 = 30 , 10 ; NEW_LINE print ( numberOfMinutes ( S , S1 ) , " min " ) ; NEW_LINE DEDENT |
Removing a number from array without changing its arithmetic mean | Function to remove a number from the array without changing its arithmetic mean ; Find sum of all elements ; If mean is an integer ; Check if mean is present in the array or not ; Driver code | def FindElement ( a , n ) : NEW_LINE INDENT s = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT s = s + a [ i ] NEW_LINE DEDENT if s % n == 0 : NEW_LINE INDENT m = s // n NEW_LINE for j in range ( n ) : NEW_LINE INDENT if a [ j ] == m : NEW_LINE INDENT return m NEW_LINE DEDENT DEDENT DEDENT return - 1 NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT a = [ 1 , 2 , 3 , 4 , 5 ] NEW_LINE n = len ( a ) NEW_LINE print ( FindElement ( a , n ) ) NEW_LINE DEDENT |
Sum of the Tan ( x ) expansion upto N terms | Function to find factorial of a number ; To store factorial of a number ; Return the factorial of a number ; Function to find tan ( x ) upto n terms ; To store value of the expansion ; This loops here calculate Bernoulli number which is further used to get the coefficient in the expansion of tan x ; Print the value of expansion ; Driver code ; Function call | def fac ( num ) : NEW_LINE INDENT if ( num == 0 ) : NEW_LINE INDENT return 1 ; NEW_LINE DEDENT fact = 1 ; NEW_LINE for i in range ( 1 , num + 1 ) : NEW_LINE INDENT fact = fact * i ; NEW_LINE DEDENT return fact ; NEW_LINE DEDENT def Tanx_expansion ( terms , x ) : NEW_LINE INDENT sum = 0 ; NEW_LINE for i in range ( 1 , terms + 1 ) : NEW_LINE INDENT B = 0 ; NEW_LINE Bn = 2 * i ; NEW_LINE for k in range ( Bn + 1 ) : NEW_LINE INDENT temp = 0 ; NEW_LINE for r in range ( 0 , k + 1 ) : NEW_LINE INDENT temp = temp + pow ( - 1 , r ) * fac ( k ) * pow ( r , Bn ) / ( fac ( r ) * fac ( k - r ) ) ; NEW_LINE DEDENT B = B + temp / ( ( k + 1 ) ) ; NEW_LINE DEDENT sum = sum + pow ( - 4 , i ) * ( 1 - pow ( 4 , i ) ) * B * pow ( x , 2 * i - 1 ) / fac ( 2 * i ) ; NEW_LINE DEDENT print ( " % .9f " % ( sum ) ) ; NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT n , x = 6 , 1 ; NEW_LINE Tanx_expansion ( n , x ) ; NEW_LINE DEDENT |
Minimum elements to be inserted in Array to make adjacent differences equal | Function to find gcd of two numbers ; Function to calculate minimum numbers to be inserted to make equal differences between two consecutive elements ; Check if there is only one element in the array then answer will be 0 ; Calculate difference between first and second element of array ; If there is only two elements in the array then gcd of differences of consecutive elements of array will be equal to difference of first and second element of the array ; Loop to calculate the gcd of the differences between consecutive elements of the array ; Loop to calculate the elements to be inserted ; Return the answer ; Driver code | def gcd ( a , b ) : NEW_LINE INDENT if ( b == 0 ) : NEW_LINE INDENT return a NEW_LINE DEDENT return gcd ( b , a % b ) NEW_LINE DEDENT def minimum_elements ( n , arr ) : NEW_LINE INDENT if ( n < 3 ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT ans = 0 NEW_LINE diff = arr [ 1 ] - arr [ 0 ] NEW_LINE g = diff NEW_LINE for i in range ( 2 , n ) : NEW_LINE INDENT diff = arr [ i ] - arr [ i - 1 ] NEW_LINE g = gcd ( g , diff ) NEW_LINE DEDENT for i in range ( 1 , n ) : NEW_LINE INDENT diff = arr [ i ] - arr [ i - 1 ] NEW_LINE cnt = diff // g NEW_LINE ans += ( cnt - 1 ) NEW_LINE DEDENT return ans NEW_LINE DEDENT arr = [ 1 , 5 , 8 , 10 , 12 , 16 ] NEW_LINE n = len ( arr ) NEW_LINE print ( minimum_elements ( n , arr ) ) NEW_LINE |
Check if a number is Fermat Pseudoprime | Python3 program to check if N is Fermat pseudoprime to the base A or not ; Function to check if the given number is composite ; Check if there is any divisor of n less than sqrt ( n ) ; Effectively calculate ( x ^ y ) modulo mod ; Initialize result ; If power is odd , then update the answer ; Square the number and reduce the power to its half ; Return the result ; Function to check for Fermat Pseudoprime ; If it is composite and satisfy Fermat criterion ; Else return 0 ; Driver code ; Function call | from math import sqrt NEW_LINE def checkcomposite ( n ) : NEW_LINE INDENT for i in range ( 2 , int ( sqrt ( n ) ) + 1 , 1 ) : NEW_LINE INDENT if ( n % i == 0 ) : NEW_LINE INDENT return 1 NEW_LINE DEDENT DEDENT return 0 NEW_LINE DEDENT def power ( x , y , mod ) : NEW_LINE INDENT res = 1 NEW_LINE while ( y ) : NEW_LINE INDENT if ( y & 1 ) : NEW_LINE INDENT res = ( res * x ) % mod NEW_LINE DEDENT y = y >> 1 NEW_LINE x = ( x * x ) % mod NEW_LINE DEDENT return res NEW_LINE DEDENT def Check ( n , a ) : NEW_LINE INDENT if ( a > 1 and checkcomposite ( n ) and power ( a , n - 1 , n ) == 1 ) : NEW_LINE INDENT return 1 NEW_LINE DEDENT return 0 NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 645 NEW_LINE a = 2 NEW_LINE print ( Check ( N , a ) ) NEW_LINE DEDENT |
Largest and smallest digit of a number | Function to the largest and smallest digit of a number ; Find the largest digit ; Find the smallest digit ; Driver code ; Function call | def Digits ( n ) : NEW_LINE INDENT largest = 0 NEW_LINE smallest = 9 NEW_LINE while ( n ) : NEW_LINE INDENT r = n % 10 NEW_LINE largest = max ( r , largest ) NEW_LINE smallest = min ( r , smallest ) NEW_LINE n = n // 10 NEW_LINE DEDENT print ( largest , smallest ) NEW_LINE DEDENT n = 2346 NEW_LINE Digits ( n ) NEW_LINE |
Probability of distributing M items among X bags such that first bag contains N items | Function to find factorial of a number ; Function to find nCr ; Function to find probability of first bag to contain N items such that M items are distributed among X bags ; Driver code ; Function call | def factorial ( n ) : NEW_LINE INDENT if ( n <= 1 ) : NEW_LINE INDENT return 1 ; NEW_LINE DEDENT return n * factorial ( n - 1 ) ; NEW_LINE DEDENT def nCr ( n , r ) : NEW_LINE INDENT return ( factorial ( n ) / ( factorial ( r ) * factorial ( n - r ) ) ) ; NEW_LINE DEDENT def Probability ( M , N , X ) : NEW_LINE INDENT return float ( nCr ( M - N - 1 , X - 2 ) / ( nCr ( M - 1 , X - 1 ) * 1.0 ) ) ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT M = 9 ; X = 3 ; N = 4 ; NEW_LINE print ( Probability ( M , N , X ) ) ; NEW_LINE DEDENT |
Count of N digit numbers possible which satisfy the given conditions | Function to return the factorial of n ; Function to return the count of numbers possible ; Driver code | def fact ( n ) : NEW_LINE INDENT res = 1 NEW_LINE for i in range ( 2 , n + 1 ) : NEW_LINE INDENT res = res * i NEW_LINE DEDENT return res NEW_LINE DEDENT def Count_number ( N ) : NEW_LINE INDENT return ( N * fact ( N ) ) NEW_LINE DEDENT N = 2 NEW_LINE print ( Count_number ( N ) ) NEW_LINE |
Find the count of M character words which have at least one character repeated | Function to return the factorial of a number ; Function to return the value of nPr ; Function to return the total number of M length words which have at least a single character repeated more than once ; Driver code | def fact ( n ) : NEW_LINE INDENT if ( n <= 1 ) : NEW_LINE INDENT return 1 ; NEW_LINE DEDENT return n * fact ( n - 1 ) ; NEW_LINE DEDENT def nPr ( n , r ) : NEW_LINE INDENT return fact ( n ) // fact ( n - r ) ; NEW_LINE DEDENT def countWords ( N , M ) : NEW_LINE INDENT return pow ( N , M ) - nPr ( N , M ) ; NEW_LINE DEDENT N = 10 ; M = 5 ; NEW_LINE print ( countWords ( N , M ) ) ; NEW_LINE |
Minimum and maximum possible length of the third side of a triangle | Function to find the minimum and the maximum possible length of the third side of the given triangle ; Not a valid triangle ; Not a valid triangle ; Driver code | def find_length ( s1 , s2 ) : NEW_LINE INDENT if ( s1 <= 0 or s2 <= 0 ) : NEW_LINE INDENT print ( - 1 , end = " " ) ; NEW_LINE return ; NEW_LINE DEDENT max_length = s1 + s2 - 1 ; NEW_LINE min_length = max ( s1 , s2 ) - min ( s1 , s2 ) + 1 ; NEW_LINE if ( min_length > max_length ) : NEW_LINE INDENT print ( - 1 , end = " " ) ; NEW_LINE return ; NEW_LINE DEDENT print ( " Max β = " , max_length ) ; NEW_LINE print ( " Min β = " , min_length ) ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT s1 = 8 ; NEW_LINE s2 = 5 ; NEW_LINE find_length ( s1 , s2 ) ; NEW_LINE DEDENT |
Number formed by the rightmost set bit in N | Function to return the integer formed by taking the rightmost set bit in n ; n & ( n - 1 ) unsets the first set bit from the right in n ; Take xor with the original number The position of the ' changed β bit ' will be set and rest will be unset ; Driver code | def firstSetBit ( n ) : NEW_LINE INDENT x = n & ( n - 1 ) NEW_LINE return ( n ^ x ) NEW_LINE DEDENT n = 12 NEW_LINE print ( firstSetBit ( n ) ) NEW_LINE |
Number of N length sequences whose product is M | Function to calculate the value of ncr effectively ; Initializing the result ; Multiply and divide simultaneously to avoid overflow ; Return the answer ; Function to return the number of sequences of length N such that their product is M ; Hashmap to store the prime factors of M ; Calculate the prime factors of M ; If i divides M it means it is a factor Divide M by i till it could be divided to store the exponent ; Increase the exponent count ; If the number is a prime number greater than sqrt ( M ) ; Initializing the ans ; Multiply the answer for every prime factor ; it . second represents the exponent of every prime factor ; Return the result ; Driver code | def ncr ( n , r ) : NEW_LINE INDENT res = 1 NEW_LINE for i in range ( 1 , r + 1 ) : NEW_LINE INDENT res *= ( n - r + i ) NEW_LINE res //= i NEW_LINE DEDENT return res NEW_LINE DEDENT def NoofSequences ( N , M ) : NEW_LINE INDENT prime = { } NEW_LINE for i in range ( 2 , int ( M ** ( .5 ) ) + 1 ) : NEW_LINE INDENT while ( M % i == 0 ) : NEW_LINE INDENT prime [ i ] = prime . get ( i , 0 ) + 1 NEW_LINE M //= i NEW_LINE DEDENT DEDENT if ( M > 1 ) : NEW_LINE INDENT prime [ M ] = prime . get ( M , 0 ) + 1 NEW_LINE DEDENT ans = 1 NEW_LINE for it in prime : NEW_LINE INDENT ans *= ( ncr ( N + prime [ it ] - 1 , N - 1 ) ) NEW_LINE DEDENT return ans NEW_LINE DEDENT N = 2 NEW_LINE M = 6 NEW_LINE print ( NoofSequences ( N , M ) ) NEW_LINE |
Number of hours after which the second person moves ahead of the first person if they travel at a given speed | Function to return the number of hours for the second person to move ahead ; Time taken to equalize ; Time taken to move ahead ; Driver code | def findHours ( a , b , k ) : NEW_LINE INDENT if ( a >= b ) : NEW_LINE INDENT return - 1 NEW_LINE DEDENT time = k // ( b - a ) NEW_LINE time = time + 1 NEW_LINE return time NEW_LINE DEDENT a = 4 NEW_LINE b = 5 NEW_LINE k = 1 NEW_LINE print ( findHours ( a , b , k ) ) NEW_LINE |
Number of ways of distributing N identical objects in R distinct groups with no groups empty | Function to return the value of ncr effectively ; Initialize the answer ; Divide simultaneously by i to avoid overflow ; Function to return the number of ways to distribute N identical objects in R distinct objects ; Driver code | def ncr ( n , r ) : NEW_LINE INDENT ans = 1 NEW_LINE for i in range ( 1 , r + 1 ) : NEW_LINE INDENT ans *= ( n - r + i ) NEW_LINE ans //= i NEW_LINE DEDENT return ans NEW_LINE DEDENT def NoOfDistributions ( N , R ) : NEW_LINE INDENT return ncr ( N - 1 , R - 1 ) NEW_LINE DEDENT N = 4 NEW_LINE R = 3 NEW_LINE print ( NoOfDistributions ( N , R ) ) NEW_LINE |
Number of ways of distributing N identical objects in R distinct groups | Function to return the value of ncr effectively ; Initialize the answer ; Divide simultaneously by i to avoid overflow ; Function to return the number of ways to distribute N identical objects in R distinct objects ; Driver code ; Function call | def ncr ( n , r ) : NEW_LINE INDENT ans = 1 NEW_LINE for i in range ( 1 , r + 1 ) : NEW_LINE INDENT ans *= ( n - r + i ) NEW_LINE ans //= i NEW_LINE DEDENT return ans NEW_LINE DEDENT def NoOfDistributions ( N , R ) : NEW_LINE INDENT return ncr ( N + R - 1 , R - 1 ) NEW_LINE DEDENT N = 4 NEW_LINE R = 3 NEW_LINE print ( NoOfDistributions ( N , R ) ) NEW_LINE |
Smallest perfect cube in an array | Python3 implementation of the approach ; Function that returns true if n is a perfect cube ; Takes the sqrt of the number ; Checks if it is a perfect cube number ; Function to return the smallest perfect cube from the array ; Stores the minimum of all the perfect cubes from the array ; Traverse all elements in the array ; Store the minimum if current element is a perfect cube ; Driver code | import sys NEW_LINE def checkPerfectcube ( n ) : NEW_LINE INDENT d = int ( n ** ( 1 / 3 ) ) ; NEW_LINE if ( d * d * d == n ) : NEW_LINE INDENT return True ; NEW_LINE DEDENT return False ; NEW_LINE DEDENT def smallestPerfectCube ( a , n ) : NEW_LINE INDENT mini = sys . maxsize ; NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( checkPerfectcube ( a [ i ] ) ) : NEW_LINE INDENT mini = min ( a [ i ] , mini ) ; NEW_LINE DEDENT DEDENT return mini ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT a = [ 16 , 8 , 25 , 2 , 3 , 10 ] ; NEW_LINE n = len ( a ) ; NEW_LINE print ( smallestPerfectCube ( a , n ) ) ; NEW_LINE DEDENT |
Find two vertices of an isosceles triangle in which there is rectangle with opposite corners ( 0 , 0 ) and ( X , Y ) | Function to find two vertices of an isosceles triangle in which there is rectangle with opposite side ( 0 , 0 ) and ( x , y ) ; Required value ; ; print x1 and y1 ; print x2 and y3 ; Driver code ; Function call | def Vertices ( x , y ) : NEW_LINE INDENT val = abs ( x ) + abs ( y ) ; NEW_LINE if x < 0 : NEW_LINE INDENT x = - 1 NEW_LINE DEDENT else : NEW_LINE INDENT x = 1 NEW_LINE DEDENT print ( val * x , "0" , end = " β " ) ; NEW_LINE if y < 0 : NEW_LINE INDENT y = - 1 NEW_LINE DEDENT else : NEW_LINE INDENT y = 1 NEW_LINE DEDENT print ( "0" , val * y ) ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT x = 3 ; y = 3 ; NEW_LINE Vertices ( x , y ) ; NEW_LINE DEDENT |
Find a subarray whose sum is divisible by size of the array | Function to find a subarray whose sum is a multiple of N ; Prefix sum array to store cumulative sum ; Single state dynamic programming relation for prefix sum array ; Generating all sub - arrays ; If the sum of the sub - array [ i : j ] is a multiple of N ; If the function reaches here it means there are no subarrays with sum as a multiple of N ; Driver code | def CheckSubarray ( arr , N ) : NEW_LINE INDENT presum = [ 0 for i in range ( N + 1 ) ] NEW_LINE for i in range ( 1 , N + 1 ) : NEW_LINE INDENT presum [ i ] = presum [ i - 1 ] + arr [ i - 1 ] NEW_LINE DEDENT for i in range ( 1 , N + 1 ) : NEW_LINE INDENT for j in range ( i , N + 1 ) : NEW_LINE INDENT if ( ( presum [ j ] - presum [ i - 1 ] ) % N == 0 ) : NEW_LINE INDENT print ( i - 1 , j - 1 ) NEW_LINE return NEW_LINE DEDENT DEDENT DEDENT print ( " - 1" ) NEW_LINE DEDENT arr = [ 7 , 5 , 3 , 7 ] NEW_LINE N = len ( arr ) NEW_LINE CheckSubarray ( arr , N ) NEW_LINE |
Find a subarray whose sum is divisible by size of the array | Function to check is there exists a subarray whose sum is a multiple of N ; Prefix sum array to store cumulative sum ; Single state dynamic programming relation for prefix sum array ; Modulo class vector ; Storing the index value in the modulo class vector ; If there exists a sub - array with starting index equal to zero ; In this class , there are more than two presums % N Hence difference of any two subarrays would be a multiple of N ; 0 based indexing ; Driver code | def CheckSubarray ( arr , N ) : NEW_LINE INDENT presum = [ 0 for i in range ( N + 1 ) ] NEW_LINE for i in range ( 1 , N + 1 ) : NEW_LINE INDENT presum [ i ] = presum [ i - 1 ] + arr [ i - 1 ] NEW_LINE DEDENT moduloclass = [ [ ] ] * N NEW_LINE for i in range ( 1 , N + 1 , 1 ) : NEW_LINE INDENT moduloclass [ presum [ i ] % N ] . append ( i - 1 ) NEW_LINE DEDENT if ( len ( moduloclass [ 0 ] ) > 0 ) : NEW_LINE INDENT print ( 0 + 1 , moduloclass [ 0 ] [ 0 ] + 2 ) NEW_LINE return NEW_LINE DEDENT for i in range ( 1 , N ) : NEW_LINE INDENT if ( len ( moduloclass [ i ] ) >= 2 ) : NEW_LINE INDENT print ( moduloclass [ i ] [ 0 ] + 1 , moduloclass [ i ] [ 1 ] ) NEW_LINE return NEW_LINE DEDENT DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 7 , 3 , 5 , 2 ] NEW_LINE N = len ( arr ) NEW_LINE CheckSubarray ( arr , N ) NEW_LINE DEDENT |
Smallest number greater or equals to N such that it has no odd positioned bit set | Function to count the total bits ; Iterate and find the number of set bits ; Right shift the number by 1 ; Function to find the nearest number ; Count the total number of bits ; To get the position ; If the last set bit is at odd position then answer will always be a number with the left bit set ; Set all the even bits which are possible ; If the number still is less than N ; Return the number by setting the next even set bit ; If we have reached this position it means tempsum > n hence turn off even bits to get the first possible number ; Turn off the bit ; If it gets lower than N then set it and return that number ; Driver code | def countBits ( n ) : NEW_LINE INDENT count = 0 ; NEW_LINE while ( n > 0 ) : NEW_LINE INDENT count += 1 ; NEW_LINE n >>= 1 ; NEW_LINE DEDENT return count ; NEW_LINE DEDENT def findNearestNumber ( n ) : NEW_LINE INDENT cnt = countBits ( n ) ; NEW_LINE cnt -= 1 ; NEW_LINE if ( cnt % 2 ) : NEW_LINE INDENT return 1 << ( cnt + 1 ) ; NEW_LINE DEDENT else : NEW_LINE INDENT tempnum = 0 ; NEW_LINE for i in range ( 0 , cnt + 1 , 2 ) : NEW_LINE INDENT tempnum += 1 << i ; NEW_LINE DEDENT if ( tempnum < n ) : NEW_LINE INDENT return ( 1 << ( cnt + 2 ) ) ; NEW_LINE DEDENT elif ( tempnum == n ) : NEW_LINE INDENT return n ; NEW_LINE DEDENT for i in range ( 0 , cnt + 1 , 2 ) : NEW_LINE INDENT tempnum -= ( 1 << i ) ; NEW_LINE if ( tempnum < n ) : NEW_LINE INDENT tempnum += ( 1 << i ) ; NEW_LINE return tempnum ; NEW_LINE DEDENT DEDENT DEDENT DEDENT n = 19 ; NEW_LINE print ( findNearestNumber ( n ) ) ; NEW_LINE |
Count of numbers whose 0 th and Nth bits are set | Function to return the count of n - bit numbers whose 0 th and nth bits are set ; Driver code | def countNum ( n ) : NEW_LINE INDENT if ( n == 1 ) : NEW_LINE INDENT return 1 NEW_LINE DEDENT count = pow ( 2 , n - 2 ) NEW_LINE return count NEW_LINE DEDENT n = 3 NEW_LINE print ( countNum ( n ) ) NEW_LINE |
Find a number containing N | Function to return the generated by appending "10" n - 1 times ; Initialising as empty ; Function to return the decimal equivaLent of the given binary string ; Initializing base value to 1 i . e 2 ^ 0 ; Function that calls the constructString and binarytodecimal and returns the answer ; Driver code | def constructString ( n ) : NEW_LINE INDENT s = " " NEW_LINE for i in range ( n ) : NEW_LINE INDENT s += "10" NEW_LINE DEDENT return s NEW_LINE DEDENT def binaryToDecimal ( n ) : NEW_LINE INDENT num = n NEW_LINE dec_value = 0 NEW_LINE base = 1 NEW_LINE Len = len ( num ) NEW_LINE for i in range ( Len - 1 , - 1 , - 1 ) : NEW_LINE INDENT if ( num [ i ] == '1' ) : NEW_LINE INDENT dec_value += base NEW_LINE DEDENT base = base * 2 NEW_LINE DEDENT return dec_value NEW_LINE DEDENT def findNumber ( n ) : NEW_LINE INDENT s = constructString ( n - 1 ) NEW_LINE num = binaryToDecimal ( s ) NEW_LINE return num NEW_LINE DEDENT n = 4 NEW_LINE print ( findNumber ( n ) ) NEW_LINE |
Bitonic point in the given linked list | Node for linked list ; Function to insert a node at the head of the linked list ; Function to return the bitonic of the given linked list ; If list is empty ; If list contains only a single node ; Invalid bitonic sequence ; If current node is the bitonic point ; Get to the next node in the list ; Nodes must be in descending starting from here ; Out of order node ; Get to the next node in the list ; Driver code | class Node : NEW_LINE INDENT def __init__ ( self , data ) : NEW_LINE INDENT self . data = data NEW_LINE self . next = None NEW_LINE DEDENT DEDENT def push ( head_ref , data ) : NEW_LINE INDENT new_node = Node ( data ) NEW_LINE new_node . next = head_ref NEW_LINE head_ref = new_node NEW_LINE return head_ref NEW_LINE DEDENT def bitonic_point ( node ) : NEW_LINE INDENT if ( node == None ) : NEW_LINE INDENT return - 1 ; NEW_LINE DEDENT if ( node . next == None ) : NEW_LINE INDENT return - 1 ; NEW_LINE DEDENT if ( node . data > node . next . data ) : NEW_LINE INDENT return - 1 ; NEW_LINE DEDENT while ( node . next != None ) : NEW_LINE INDENT if ( node . data > node . next . data ) : NEW_LINE INDENT break ; NEW_LINE DEDENT node = node . next ; NEW_LINE DEDENT bitonicPoint = node . data ; NEW_LINE while ( node . next != None ) : NEW_LINE INDENT if ( node . data < node . next . data ) : NEW_LINE INDENT return - 1 ; NEW_LINE DEDENT node = node . next ; NEW_LINE DEDENT return bitonicPoint ; NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT head = None ; NEW_LINE head = push ( head , 100 ) ; NEW_LINE head = push ( head , 201 ) ; NEW_LINE head = push ( head , 399 ) ; NEW_LINE head = push ( head , 490 ) ; NEW_LINE head = push ( head , 377 ) ; NEW_LINE head = push ( head , 291 ) ; NEW_LINE head = push ( head , 100 ) ; NEW_LINE print ( bitonic_point ( head ) ) NEW_LINE DEDENT |
Find the minimum number of elements that should be removed to make an array good | Function to remove minimum elements to make the given array good ; To store count of each subsequence ; Increase the count of subsequence [ 0 ] ; If Previous element subsequence count is greater than zero then increment subsequence count of current element and decrement subsequence count of the previous element . ; Return the required answer ; Driver code ; Function call | def MinRemove ( a , n , k ) : NEW_LINE INDENT cnt = [ 0 ] * k NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( a [ i ] == 0 ) : NEW_LINE INDENT cnt [ 0 ] += 1 ; NEW_LINE DEDENT elif ( cnt [ a [ i ] - 1 ] > 0 ) : NEW_LINE INDENT cnt [ a [ i ] - 1 ] -= 1 ; NEW_LINE cnt [ a [ i ] ] += 1 ; NEW_LINE DEDENT DEDENT return n - ( k * cnt [ k - 1 ] ) ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT a = [ 0 , 1 , 2 , 3 , 4 , 0 , 1 , 0 , 1 , 2 , 3 , 4 ] NEW_LINE k = 5 ; NEW_LINE n = len ( a ) ; NEW_LINE print ( MinRemove ( a , n , k ) ) ; NEW_LINE DEDENT |
Print first N Mosaic numbers | Function to return the nth mosaic number ; Iterate from 2 to the number ; If i is the factor of n ; Find the count where i ^ count is a factor of n ; Divide the number by i ; Increase the count ; Multiply the answer with count and i ; Return the answer ; Function to print first N Mosaic numbers ; Driver code | def mosaic ( n ) : NEW_LINE INDENT ans = 1 NEW_LINE for i in range ( 2 , n + 1 ) : NEW_LINE INDENT if ( n % i == 0 and n > 0 ) : NEW_LINE INDENT count = 0 ; NEW_LINE while ( n % i == 0 ) : NEW_LINE INDENT n = n // i NEW_LINE count += 1 ; NEW_LINE DEDENT ans *= count * i ; NEW_LINE DEDENT DEDENT return ans ; NEW_LINE DEDENT def nMosaicNumbers ( n ) : NEW_LINE INDENT for i in range ( 1 , n + 1 ) : NEW_LINE INDENT print mosaic ( i ) , NEW_LINE DEDENT DEDENT n = 10 ; NEW_LINE nMosaicNumbers ( n ) ; NEW_LINE |
Count of nodes which are at a distance X from root and leaves | Python3 implementation of the approach ; Function to find the count of the required nodes ; Height of the complete binary tree with n nodes ; If X > height then no node can be present at that level ; Corner case ; Maximum total nodes that are possible in complete binary tree with height h ; Nodes at the last level ; To store the count of nodes x dist away from root ; To store the count of nodes x dist away from leaf ; If X = h then prnodes at last level else nodes at Xth level ; 2 ^ X ; Number of left leaf nodes at ( h - 1 ) th level observe that if nodes are not present at last level then there are a / 2 leaf nodes at ( h - 1 ) th level ; If X = h then prleaf nodes at the last h level + leaf nodes at ( h - 1 ) th level ; First calculate nodes for leaves present at height h ; Then calculate nodes for leaves present at height h - 1 ; Add both the resuls ; Driver code | from math import log2 , ceil , floor NEW_LINE def countNodes ( N , X ) : NEW_LINE INDENT height = floor ( log2 ( N ) ) NEW_LINE if ( X > height ) : NEW_LINE INDENT print ( " 0 0 " ) NEW_LINE return NEW_LINE DEDENT if ( N == 1 ) : NEW_LINE INDENT print ( " 1 1 " ) NEW_LINE return NEW_LINE DEDENT max_total_nodes = ( 1 << ( height + 1 ) ) - 1 NEW_LINE nodes_last_level = ( 1 << height ) - ( max_total_nodes - N ) NEW_LINE from_root = 0 NEW_LINE from_leaf = 0 NEW_LINE if ( X == height ) : NEW_LINE INDENT from_root = nodes_last_level NEW_LINE DEDENT else : NEW_LINE INDENT from_root = 1 << X NEW_LINE DEDENT left_leaf_nodes = ( ( 1 << height ) - nodes_last_level ) // 2 NEW_LINE if ( X == 0 ) : NEW_LINE INDENT from_leaf = nodes_last_level + left_leaf_nodes NEW_LINE DEDENT else : NEW_LINE INDENT i = X NEW_LINE while ( nodes_last_level > 1 and i > 0 ) : NEW_LINE INDENT nodes_last_level = ceil ( nodes_last_level / 2 ) NEW_LINE i -= 1 NEW_LINE DEDENT from_leaf = nodes_last_level NEW_LINE i = X NEW_LINE while ( left_leaf_nodes > 1 and i > 0 ) : NEW_LINE INDENT left_leaf_nodes = ceil ( left_leaf_nodes / 2 ) NEW_LINE i -= 1 NEW_LINE DEDENT from_leaf += left_leaf_nodes NEW_LINE DEDENT print ( from_root ) NEW_LINE print ( from_leaf ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N , X = 38 , 3 NEW_LINE countNodes ( N , X ) NEW_LINE DEDENT |
Number of ways of writing N as a sum of 4 squares | Number of ways of writing n as a sum of 4 squares ; sum of odd and even factor ; iterate from 1 to the number ; if i is the factor of n ; if factor is even ; if factor is odd ; n / i is also a factor ; if factor is even ; if factor is odd ; if n is odd ; if n is even ; Driver code | def sum_of_4_squares ( n ) : NEW_LINE INDENT i , odd , even = 0 , 0 , 0 NEW_LINE for i in range ( 1 , int ( n ** ( .5 ) ) + 1 ) : NEW_LINE INDENT if ( n % i == 0 ) : NEW_LINE INDENT if ( i % 2 == 0 ) : NEW_LINE INDENT even += i NEW_LINE DEDENT else : NEW_LINE INDENT odd += i NEW_LINE DEDENT if ( ( n // i ) != i ) : NEW_LINE INDENT if ( ( n // i ) % 2 == 0 ) : NEW_LINE INDENT even += ( n // i ) NEW_LINE DEDENT else : NEW_LINE INDENT odd += ( n // i ) NEW_LINE DEDENT DEDENT DEDENT DEDENT if ( n % 2 == 1 ) : NEW_LINE INDENT return 8 * ( odd + even ) NEW_LINE DEDENT else : NEW_LINE INDENT return 24 * ( odd ) NEW_LINE DEDENT DEDENT n = 4 NEW_LINE print ( sum_of_4_squares ( n ) ) NEW_LINE |
Find the Nth Mosaic number | Function to return the nth mosaic number ; Iterate from 2 to the number ; If i is the factor of n ; Find the count where i ^ count is a factor of n ; Divide the number by i ; Increase the count ; Multiply the answer with count and i ; Return the answer ; Driver code | def mosaic ( n ) : NEW_LINE INDENT i = 0 NEW_LINE ans = 1 NEW_LINE for i in range ( 2 , n + 1 ) : NEW_LINE INDENT if ( n % i == 0 and n > 0 ) : NEW_LINE INDENT count = 0 NEW_LINE while ( n % i == 0 ) : NEW_LINE INDENT n //= i NEW_LINE count += 1 NEW_LINE DEDENT ans *= count * i NEW_LINE DEDENT DEDENT return ans NEW_LINE DEDENT n = 36 NEW_LINE print ( mosaic ( n ) ) NEW_LINE |
Seating arrangement of N boys sitting around a round table such that two particular boys sit together | Function to return the total count of ways ; Find ( n - 1 ) factorial ; Return ( n - 1 ) ! * 2 ! ; Driver code | def Total_Ways ( n ) : NEW_LINE INDENT fac = 1 ; NEW_LINE for i in range ( 2 , n ) : NEW_LINE INDENT fac = fac * i ; NEW_LINE DEDENT return ( fac * 2 ) ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT n = 5 ; NEW_LINE print ( Total_Ways ( n ) ) ; NEW_LINE DEDENT |
Find the maximum number of elements divisible by 3 | Function to find the maximum number of elements divisible by 3 ; To store frequency of each number ; Store modulo value ; Store frequency ; Add numbers with zero modulo to answer ; Find minimum of elements with modulo frequency one and zero ; Add k to the answer ; Remove them from frequency ; Add numbers possible with remaining frequency ; Return the required answer ; Driver code ; Function call | def MaxNumbers ( a , n ) : NEW_LINE INDENT fre = [ 0 for i in range ( 3 ) ] NEW_LINE for i in range ( n ) : NEW_LINE INDENT a [ i ] %= 3 NEW_LINE fre [ a [ i ] ] += 1 NEW_LINE DEDENT ans = fre [ 0 ] NEW_LINE k = min ( fre [ 1 ] , fre [ 2 ] ) NEW_LINE ans += k NEW_LINE fre [ 1 ] -= k NEW_LINE fre [ 2 ] -= k NEW_LINE ans += fre [ 1 ] // 3 + fre [ 2 ] // 3 NEW_LINE return ans NEW_LINE DEDENT a = [ 1 , 4 , 10 , 7 , 11 , 2 , 8 , 5 , 9 ] NEW_LINE n = len ( a ) NEW_LINE print ( MaxNumbers ( a , n ) ) NEW_LINE |
Count pairs with set bits sum equal to K | Function to return the count of set bits in n ; Function to return the count of required pairs ; To store the count ; Sum of set bits in both the integers ; If current pair satisfies the given condition ; Driver code | def countSetBits ( n ) : NEW_LINE INDENT count = 0 ; NEW_LINE while ( n ) : NEW_LINE INDENT n &= ( n - 1 ) ; NEW_LINE count += 1 NEW_LINE DEDENT return count ; NEW_LINE DEDENT def pairs ( arr , n , k ) : NEW_LINE INDENT count = 0 ; NEW_LINE for i in range ( n ) : NEW_LINE INDENT for j in range ( i + 1 , n ) : NEW_LINE INDENT sum = countSetBits ( arr [ i ] ) + countSetBits ( arr [ j ] ) ; NEW_LINE if ( sum == k ) : NEW_LINE INDENT count += 1 ; NEW_LINE DEDENT DEDENT DEDENT return count ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 1 , 2 , 3 , 4 , 5 ] ; NEW_LINE n = len ( arr ) ; NEW_LINE k = 4 ; NEW_LINE print ( pairs ( arr , n , k ) ) ; NEW_LINE DEDENT |
Count pairs with set bits sum equal to K | Python implementation of the approach ; Function to return the count of set bits in n ; Function to return the count of required pairs ; To store the count ; Frequency array ; If current pair satisfies the given condition ; ( arr [ i ] , arr [ i ] ) cannot be a valid pair ; Driver code | MAX = 32 NEW_LINE def countSetBits ( n ) : NEW_LINE INDENT count = 0 ; NEW_LINE while ( n ) : NEW_LINE INDENT n &= ( n - 1 ) ; NEW_LINE count += 1 ; NEW_LINE DEDENT return count ; NEW_LINE DEDENT def pairs ( arr , n , k ) : NEW_LINE INDENT count = 0 ; NEW_LINE f = [ 0 for i in range ( MAX + 1 ) ] NEW_LINE for i in range ( n ) : NEW_LINE INDENT f [ countSetBits ( arr [ i ] ) ] += 1 ; NEW_LINE DEDENT for i in range ( MAX + 1 ) : NEW_LINE INDENT for j in range ( 1 , MAX + 1 ) : NEW_LINE INDENT if ( i + j == k ) : NEW_LINE INDENT if ( i == j ) : NEW_LINE INDENT count += ( ( f [ i ] * ( f [ i ] - 1 ) ) / 2 ) ; NEW_LINE DEDENT else : NEW_LINE INDENT count += ( f [ i ] * f [ j ] ) ; NEW_LINE DEDENT DEDENT DEDENT DEDENT return count ; NEW_LINE DEDENT arr = [ 1 , 2 , 3 , 4 , 5 ] NEW_LINE n = len ( arr ) NEW_LINE k = 4 NEW_LINE print ( pairs ( arr , n , k ) ) NEW_LINE |
Print Lower Hessenberg matrix of order N | Python3 implementation of the approach ; Function to print the Upper Hessenberg matrix of order n ; If element is below sub - diagonal then pr0 ; Pra random digit for every non - zero element ; Driver code | import random NEW_LINE def UpperHessenbergMatrix ( n ) : NEW_LINE INDENT for i in range ( 1 , n + 1 ) : NEW_LINE INDENT for j in range ( 1 , n + 1 ) : NEW_LINE INDENT if ( j > i + 1 ) : NEW_LINE INDENT print ( '0' , end = " β " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( random . randint ( 1 , 10 ) , end = " β " ) NEW_LINE DEDENT DEDENT print ( ) NEW_LINE DEDENT DEDENT n = 4 ; NEW_LINE UpperHessenbergMatrix ( n ) NEW_LINE |
Print Upper Hessenberg matrix of order N | Python3 implementation of the approach ; Function to print the Upper Hessenberg matrix of order n ; If element is below sub - diagonal then pr0 ; Pra random digit for every non - zero element ; Driver code | import random NEW_LINE def UpperHessenbergMatrix ( n ) : NEW_LINE INDENT for i in range ( 1 , n + 1 ) : NEW_LINE INDENT for j in range ( 1 , n + 1 ) : NEW_LINE INDENT if ( i > j + 1 ) : NEW_LINE INDENT print ( '0' , end = " β " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( random . randint ( 1 , 10 ) , end = " β " ) NEW_LINE DEDENT DEDENT print ( ) NEW_LINE DEDENT DEDENT n = 4 ; NEW_LINE UpperHessenbergMatrix ( n ) NEW_LINE |
Find the total number of composite factor for a given number | Function to return the count of prime factors of n ; Initialise array with 0 ; Stored i value into an array ; Every non - zero value at a [ i ] denotes that i is a factor of n ; Find if i is prime ; If i is a factor of n and i is not prime ; Driver code | def composite_factors ( n ) : NEW_LINE INDENT count = 0 ; NEW_LINE a = [ 0 ] * ( n + 1 ) ; NEW_LINE for i in range ( 1 , n + 1 ) : NEW_LINE INDENT if ( n % i == 0 ) : NEW_LINE INDENT a [ i ] = i ; NEW_LINE DEDENT DEDENT for i in range ( 2 , n + 1 ) : NEW_LINE INDENT j = 2 ; NEW_LINE p = 1 ; NEW_LINE while ( j < a [ i ] ) : NEW_LINE INDENT if ( a [ i ] % j == 0 ) : NEW_LINE INDENT p = 0 ; NEW_LINE break ; NEW_LINE DEDENT j += 1 ; NEW_LINE DEDENT if ( p == 0 and a [ i ] != 0 ) : NEW_LINE INDENT count += 1 ; NEW_LINE DEDENT DEDENT return count ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT n = 100 ; NEW_LINE print ( composite_factors ( n ) ) ; NEW_LINE DEDENT |
Sum of all mersenne numbers present in an array | Function that returns true if n is a Mersenne number ; Function to return the sum of all the Mersenne numbers from the given array ; To store the required sum ; If current element is a Mersenne number ; Driver code | def isMersenne ( n ) : NEW_LINE INDENT while ( n != 0 ) : NEW_LINE INDENT r = n % 2 ; NEW_LINE if ( r == 0 ) : NEW_LINE INDENT return False ; NEW_LINE DEDENT n //= 2 ; NEW_LINE DEDENT return True ; NEW_LINE DEDENT def sumOfMersenne ( arr , n ) : NEW_LINE INDENT sum = 0 ; NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( arr [ i ] > 0 and isMersenne ( arr [ i ] ) ) : NEW_LINE INDENT sum += arr [ i ] ; NEW_LINE DEDENT DEDENT return sum ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 17 , 6 , 7 , 63 , 3 ] ; NEW_LINE n = len ( arr ) ; NEW_LINE print ( sumOfMersenne ( arr , n ) ) ; NEW_LINE DEDENT |
Sum of all perfect numbers present in an array | Function to return the sum of all the proper factors of n ; f is the factor of n ; Function to return the required sum ; To store the sum ; If current element is non - zero and equal to the sum of proper factors of itself ; Driver code | def sumOfFactors ( n ) : NEW_LINE INDENT sum = 0 NEW_LINE for f in range ( 1 , n // 2 + 1 ) : NEW_LINE INDENT if ( n % f == 0 ) : NEW_LINE INDENT sum += f NEW_LINE DEDENT DEDENT return sum NEW_LINE DEDENT def getSum ( arr , n ) : NEW_LINE INDENT sum = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( arr [ i ] > 0 and arr [ i ] == sumOfFactors ( arr [ i ] ) ) : NEW_LINE INDENT sum += arr [ i ] NEW_LINE DEDENT DEDENT return sum NEW_LINE DEDENT arr = [ 17 , 6 , 10 , 6 , 4 ] NEW_LINE n = len ( arr ) NEW_LINE print ( getSum ( arr , n ) ) NEW_LINE |
Check if two numbers have same number of digits | Function that return true if A and B have same number of digits ; Both must be 0 now if they had same lengths ; Driver code | def sameLength ( A , B ) : NEW_LINE INDENT while ( A > 0 and B > 0 ) : NEW_LINE INDENT A = A / 10 ; NEW_LINE B = B / 10 ; NEW_LINE DEDENT if ( A == 0 and B == 0 ) : NEW_LINE INDENT return True ; NEW_LINE DEDENT return False ; NEW_LINE DEDENT A = 21 ; B = 1 ; NEW_LINE if ( sameLength ( A , B ) ) : NEW_LINE INDENT print ( " Yes " ) ; NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) ; NEW_LINE DEDENT |
Queries to check whether all the elements can be made positive by flipping signs exactly K times | To store the count of negative integers ; Check if zero exists ; Function to find the count of negative integers and check if zero exists in the array ; Function that returns true if array elements can be made positive by changing signs exactly k times ; Driver code ; Pre - processing ; Perform queries | cnt_neg = 0 ; NEW_LINE exists_zero = None ; NEW_LINE def preProcess ( arr , n ) : NEW_LINE INDENT global cnt_neg NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( arr [ i ] < 0 ) : NEW_LINE INDENT cnt_neg += 1 ; NEW_LINE DEDENT if ( arr [ i ] == 0 ) : NEW_LINE INDENT exists_zero = True ; NEW_LINE DEDENT DEDENT DEDENT def isPossible ( k ) : NEW_LINE INDENT if ( not exists_zero ) : NEW_LINE INDENT if ( k >= cnt_neg and ( k - cnt_neg ) % 2 == 0 ) : NEW_LINE INDENT return True ; NEW_LINE DEDENT else : NEW_LINE INDENT return False ; NEW_LINE DEDENT DEDENT else : NEW_LINE INDENT if ( k >= cnt_neg ) : NEW_LINE INDENT return True ; NEW_LINE DEDENT else : NEW_LINE INDENT return False ; NEW_LINE DEDENT DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ - 1 , 2 , - 3 , 4 , 5 ] ; NEW_LINE n = len ( arr ) ; NEW_LINE preProcess ( arr , n ) ; NEW_LINE queries = [ 1 , 2 , 3 , 4 ] ; NEW_LINE q = len ( queries ) ; NEW_LINE for i in range ( q ) : NEW_LINE INDENT if ( isPossible ( queries [ i ] ) ) : NEW_LINE INDENT print ( " Yes " ) ; NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) ; NEW_LINE DEDENT DEDENT DEDENT |
Sum of XOR of all sub | Sum of XOR of all K length sub - array of an array ; If the length of the array is less than k ; Array that will store xor values of subarray from 1 to i ; Traverse through the array ; If i is greater than zero , store xor of all the elements from 0 to i ; If it is the first element ; If i is greater than k ; Xor of values from 0 to i ; Now to find subarray of length k that ends at i , xor sum with x [ i - k ] ; Add the xor of elements from i - k + 1 to i ; Return the resultant sum ; ; Driver code | def FindXorSum ( arr , k , n ) : NEW_LINE INDENT if ( n < k ) : NEW_LINE INDENT return 0 ; NEW_LINE DEDENT x = [ 0 ] * n ; NEW_LINE result = 0 ; NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( i > 0 ) : NEW_LINE INDENT x [ i ] = x [ i - 1 ] ^ arr [ i ] ; NEW_LINE DEDENT else : NEW_LINE INDENT x [ i ] = arr [ i ] ; NEW_LINE DEDENT if ( i >= k - 1 ) : NEW_LINE INDENT sum = 0 ; NEW_LINE sum = x [ i ] ; NEW_LINE if ( i - k > - 1 ) : NEW_LINE INDENT sum ^= x [ i - k ] ; NEW_LINE DEDENT result += sum ; NEW_LINE DEDENT DEDENT return result ; NEW_LINE DEDENT arr = [ 1 , 2 , 3 , 4 ] ; NEW_LINE n = 4 ; k = 2 ; NEW_LINE print ( FindXorSum ( arr , k , n ) ) ; NEW_LINE |
Count the number of digits of palindrome numbers in an array | Function to return the reverse of n ; Function that returns true if n is a palindrome ; Function to return the count of digits of n ; Function to return the count of digits in all the palindromic numbers of arr [ ] ; If arr [ i ] is a one digit number or it is a palindrome ; Driver code | def reverse ( n ) : NEW_LINE INDENT rev = 0 ; NEW_LINE while ( n > 0 ) : NEW_LINE INDENT d = n % 10 ; NEW_LINE rev = rev * 10 + d ; NEW_LINE n = n // 10 ; NEW_LINE DEDENT return rev ; NEW_LINE DEDENT def isPalin ( n ) : NEW_LINE INDENT return ( n == reverse ( n ) ) ; NEW_LINE DEDENT def countDigits ( n ) : NEW_LINE INDENT c = 0 ; NEW_LINE while ( n > 0 ) : NEW_LINE INDENT n = n // 10 ; NEW_LINE c += 1 ; NEW_LINE DEDENT return c ; NEW_LINE DEDENT def countPalinDigits ( arr , n ) : NEW_LINE INDENT s = 0 ; NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( arr [ i ] < 10 or isPalin ( arr [ i ] ) ) : NEW_LINE INDENT s += countDigits ( arr [ i ] ) ; NEW_LINE DEDENT DEDENT return s ; NEW_LINE DEDENT arr = [ 121 , 56 , 434 ] ; NEW_LINE n = len ( arr ) ; NEW_LINE print ( countPalinDigits ( arr , n ) ) ; NEW_LINE |
Sum of all palindrome numbers present in an Array | Function to reverse a number n ; Function to check if a number n is palindrome ; If n is equal to the reverse of n it is a palindrome ; Function to calculate sum of all array elements which are palindrome ; summation of all palindrome numbers present in array ; Driver Code | def reverse ( n ) : NEW_LINE INDENT d = 0 ; s = 0 ; NEW_LINE while ( n > 0 ) : NEW_LINE INDENT d = n % 10 ; NEW_LINE s = s * 10 + d ; NEW_LINE n = n // 10 ; NEW_LINE DEDENT return s ; NEW_LINE DEDENT def isPalin ( n ) : NEW_LINE INDENT return n == reverse ( n ) ; NEW_LINE DEDENT def sumOfArray ( arr , n ) : NEW_LINE INDENT s = 0 ; NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( ( arr [ i ] > 10 ) and isPalin ( arr [ i ] ) ) : NEW_LINE INDENT s += arr [ i ] ; NEW_LINE DEDENT DEDENT return s ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT n = 6 ; NEW_LINE arr = [ 12 , 313 , 11 , 44 , 9 , 1 ] ; NEW_LINE print ( sumOfArray ( arr , n ) ) ; NEW_LINE DEDENT |
Queries for the difference between the count of composite and prime numbers in a given range | Python3 implementation of the approach ; Function to update prime [ ] such prime [ i ] stores the count of prime numbers <= i ; Initialization ; 0 and 1 are not primes ; Mark composite numbers as false and prime numbers as true ; Update prime [ ] such that prime [ i ] will store the count of all the prime numbers <= i ; Function to return the absolute difference between the number of primes and the number of composite numbers in the range [ l , r ] ; Total elements in the range ; Count of primes in the range [ l , r ] ; Count of composite numbers in the range [ l , r ] ; Return the sbsolute difference ; Driver code ; Perform queries | from math import sqrt NEW_LINE MAX = 1000000 NEW_LINE prime = [ 0 ] * ( MAX + 1 ) ; NEW_LINE def updatePrimes ( ) : NEW_LINE INDENT for i in range ( 2 , MAX + 1 ) : NEW_LINE INDENT prime [ i ] = 1 ; NEW_LINE DEDENT prime [ 0 ] = prime [ 1 ] = 0 ; NEW_LINE for i in range ( 2 , int ( sqrt ( MAX ) + 1 ) ) : NEW_LINE INDENT if ( prime [ i ] == 1 ) : NEW_LINE INDENT for j in range ( i * i , MAX , i ) : NEW_LINE INDENT prime [ j ] = 0 ; NEW_LINE DEDENT DEDENT DEDENT for i in range ( 1 , MAX ) : NEW_LINE INDENT prime [ i ] += prime [ i - 1 ] ; NEW_LINE DEDENT DEDENT def getDifference ( l , r ) : NEW_LINE INDENT total = r - l + 1 ; NEW_LINE primes = prime [ r ] - prime [ l - 1 ] ; NEW_LINE composites = total - primes ; NEW_LINE return ( abs ( primes - composites ) ) ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT queries = [ [ 1 , 10 ] , [ 5 , 30 ] ] ; NEW_LINE q = len ( queries ) ; NEW_LINE updatePrimes ( ) ; NEW_LINE for i in range ( q ) : NEW_LINE INDENT print ( getDifference ( queries [ i ] [ 0 ] , queries [ i ] [ 1 ] ) ) NEW_LINE DEDENT DEDENT |
Check if the given Prufer sequence is valid or not | Function that returns true if given Prufer sequence is valid ; Iterate in the Prufer sequence ; If out of range ; Driver code | def isValidSeq ( a , n ) : NEW_LINE INDENT nodes = n + 2 ; NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( a [ i ] < 1 or a [ i ] > nodes ) : NEW_LINE INDENT return False ; NEW_LINE DEDENT DEDENT return True ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT a = [ 4 , 1 , 3 , 4 ] ; NEW_LINE n = len ( a ) ; NEW_LINE if ( isValidSeq ( a , n ) ) : NEW_LINE INDENT print ( " Valid " ) ; NEW_LINE DEDENT else : NEW_LINE INDENT print ( " Invalid " ) ; NEW_LINE DEDENT DEDENT |
Program to Calculate e ^ x by Recursion ( using Taylor Series ) | Recursive Function global variables p and f ; Termination condition ; Recursive call ; Update the power of x ; Factorial ; Driver code | p = 1.0 NEW_LINE f = 1.0 NEW_LINE def e ( x , n ) : NEW_LINE INDENT global p , f NEW_LINE if ( n == 0 ) : NEW_LINE INDENT return 1 NEW_LINE DEDENT r = e ( x , n - 1 ) NEW_LINE p = p * x NEW_LINE f = f * n NEW_LINE return ( r + p / f ) NEW_LINE DEDENT x = 4 NEW_LINE n = 15 NEW_LINE print ( e ( x , n ) ) NEW_LINE |
Check if each element of the given array is the product of exactly K prime numbers | Python3 program to check if each element of the given array is a product of exactly K prime factors ; initialise the global sieve array ; Function to generate Sieve ; NOTE : k value is necessarily more than 1 hence , 0 , 1 and any prime number cannot be represented as product of two or more prime numbers ; Function to check if each number of array satisfies the given condition ; Driver Code ; first construct the sieve | MAX = 1000000 NEW_LINE Sieve = [ 0 ] * ( MAX + 1 ) NEW_LINE def constructSieve ( ) : NEW_LINE INDENT for i in range ( 2 , MAX + 1 ) : NEW_LINE INDENT if ( Sieve [ i ] == 0 ) : NEW_LINE INDENT for j in range ( 2 * i , MAX + 1 , i ) : NEW_LINE INDENT temp = j ; NEW_LINE while ( temp > 1 and temp % i == 0 ) : NEW_LINE INDENT Sieve [ j ] += 1 ; NEW_LINE temp = temp // i ; NEW_LINE DEDENT DEDENT DEDENT DEDENT DEDENT def checkElements ( A , n , k ) : NEW_LINE INDENT for i in range ( n ) : NEW_LINE INDENT if ( Sieve [ A [ i ] ] == k ) : NEW_LINE INDENT print ( " YES " ) ; NEW_LINE DEDENT else : NEW_LINE INDENT print ( " NO " ) ; NEW_LINE DEDENT DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT constructSieve ( ) ; NEW_LINE k = 3 ; NEW_LINE A = [ 12 , 36 , 42 , 72 ] ; NEW_LINE n = len ( A ) ; NEW_LINE checkElements ( A , n , k ) ; NEW_LINE DEDENT |
Fibonacci Power | ; Iterative function to compute modular power ; Initialize result ; Update x if it is more than or equal to p ; If y is odd , multiply x with result ; y must be even now ; Helper function that multiplies 2 matrices F and M of size 2 * 2 , and puts the multiplication result back to F [ ] [ ] ; Helper function that calculates F [ ] [ ] raise to the power n and puts the result in F [ ] [ ] Note that this function is designed only for fib ( ) and won 't work as general power function ; Function that returns nth Fibonacci number ; Driver Code | mod = 1000000007 ; NEW_LINE def modularexpo ( x , y , p ) : NEW_LINE INDENT res = 1 ; NEW_LINE x = x % p ; NEW_LINE while ( y > 0 ) : NEW_LINE INDENT if ( y & 1 ) : NEW_LINE INDENT res = ( res * x ) % p ; NEW_LINE DEDENT y = y >> 1 ; NEW_LINE x = ( x * x ) % p ; NEW_LINE DEDENT return res ; NEW_LINE DEDENT def multiply ( F , M , m ) : NEW_LINE INDENT x = ( ( F [ 0 ] [ 0 ] * M [ 0 ] [ 0 ] ) % m + ( F [ 0 ] [ 1 ] * M [ 1 ] [ 0 ] ) % m ) % m ; NEW_LINE y = ( ( F [ 0 ] [ 0 ] * M [ 0 ] [ 1 ] ) % m + ( F [ 0 ] [ 1 ] * M [ 1 ] [ 1 ] ) % m ) % m ; NEW_LINE z = ( ( F [ 1 ] [ 0 ] * M [ 0 ] [ 0 ] ) % m + ( F [ 1 ] [ 1 ] * M [ 1 ] [ 0 ] ) % m ) % m ; NEW_LINE w = ( ( F [ 1 ] [ 0 ] * M [ 0 ] [ 1 ] ) % m + ( F [ 1 ] [ 1 ] * M [ 1 ] [ 1 ] ) % m ) % m ; NEW_LINE F [ 0 ] [ 0 ] = x ; NEW_LINE F [ 0 ] [ 1 ] = y ; NEW_LINE F [ 1 ] [ 0 ] = z ; NEW_LINE F [ 1 ] [ 1 ] = w ; NEW_LINE DEDENT def power ( F , n , m ) : NEW_LINE INDENT if ( n == 0 or n == 1 ) : NEW_LINE INDENT return ; NEW_LINE DEDENT M = [ [ 1 , 1 ] , [ 1 , 0 ] ] ; NEW_LINE power ( F , n // 2 , m ) ; NEW_LINE multiply ( F , F , m ) ; NEW_LINE if ( n % 2 != 0 ) : NEW_LINE INDENT multiply ( F , M , m ) ; NEW_LINE DEDENT DEDENT def fib ( n , m ) : NEW_LINE INDENT F = [ [ 1 , 1 ] , [ 1 , 0 ] ] ; NEW_LINE if ( n == 0 ) : NEW_LINE INDENT return 0 ; NEW_LINE DEDENT power ( F , n - 1 , m ) ; NEW_LINE return F [ 0 ] [ 0 ] ; NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT n = 4 ; NEW_LINE base = fib ( n , mod ) % mod ; NEW_LINE expo = fib ( n , mod - 1 ) % ( mod - 1 ) ; NEW_LINE result = modularexpo ( base , expo , mod ) % mod ; NEW_LINE print ( result ) ; NEW_LINE DEDENT |
Count number of ways to divide an array into two halves with same sum | Function to count the number of ways to divide an array into two halves with same sum ; if length of array is 1 answer will be 0 as we have to split it into two non - empty halves ; variables to store total sum , current sum and count ; finding total sum ; checking if sum equals total_sum / 2 ; Driver Code | def cntWays ( arr , n ) : NEW_LINE INDENT if ( n == 1 ) : NEW_LINE INDENT return 0 ; NEW_LINE DEDENT tot_sum = 0 ; sum = 0 ; ans = 0 ; NEW_LINE for i in range ( 0 , n ) : NEW_LINE INDENT tot_sum += arr [ i ] ; NEW_LINE DEDENT for i in range ( 0 , n - 1 ) : NEW_LINE INDENT sum += arr [ i ] ; NEW_LINE if ( sum == tot_sum / 2 ) : NEW_LINE INDENT ans += 1 ; NEW_LINE DEDENT DEDENT return ans ; NEW_LINE DEDENT arr = [ 1 , - 1 , 1 , - 1 , 1 , - 1 ] ; NEW_LINE n = len ( arr ) ; NEW_LINE print ( cntWays ( arr , n ) ) ; NEW_LINE |
Find N distinct numbers whose bitwise Or is equal to K | Pyhton 3 implementation of the approach ; Function to pre - calculate all the powers of 2 upto MAX ; Function to return the count of set bits in x ; To store the count of set bits ; Function to add num to the answer by setting all bit positions as 0 which are also 0 in K ; Bit i is 0 in K ; Function to find and print N distinct numbers whose bitwise OR is K ; Choosing K itself as one number ; Find the count of set bits in K ; Impossible to get N distinct integers ; Add i to the answer after setting all the bits as 0 which are 0 in K ; If N distinct numbers are generated ; Print the generated numbers ; Driver code ; Pre - calculate all the powers of 2 | MAX = 32 NEW_LINE pow2 = [ 0 for i in range ( MAX ) ] NEW_LINE visited = [ False for i in range ( MAX ) ] NEW_LINE ans = [ ] NEW_LINE def power_2 ( ) : NEW_LINE INDENT an = 1 NEW_LINE for i in range ( MAX ) : NEW_LINE INDENT pow2 [ i ] = an NEW_LINE an *= 2 NEW_LINE DEDENT DEDENT def countSetBits ( x ) : NEW_LINE INDENT setBits = 0 NEW_LINE while ( x != 0 ) : NEW_LINE INDENT x = x & ( x - 1 ) NEW_LINE setBits += 1 NEW_LINE DEDENT return setBits NEW_LINE DEDENT def add ( num ) : NEW_LINE INDENT point = 0 NEW_LINE value = 0 NEW_LINE for i in range ( MAX ) : NEW_LINE INDENT if ( visited [ i ] ) : NEW_LINE INDENT continue NEW_LINE DEDENT else : NEW_LINE INDENT if ( num & 1 ) : NEW_LINE INDENT value += ( 1 << i ) NEW_LINE DEDENT num = num // 2 NEW_LINE DEDENT DEDENT ans . append ( value ) NEW_LINE DEDENT def solve ( n , k ) : NEW_LINE INDENT ans . append ( k ) NEW_LINE countk = countSetBits ( k ) NEW_LINE if ( pow2 [ countk ] < n ) : NEW_LINE INDENT print ( - 1 ) NEW_LINE return NEW_LINE DEDENT count = 0 NEW_LINE for i in range ( pow2 [ countk ] - 1 ) : NEW_LINE INDENT add ( i ) NEW_LINE count += 1 NEW_LINE if ( count == n ) : NEW_LINE INDENT break NEW_LINE DEDENT DEDENT for i in range ( n ) : NEW_LINE INDENT print ( ans [ i ] , end = " β " ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT n = 3 NEW_LINE k = 5 NEW_LINE power_2 ( ) NEW_LINE solve ( n , k ) NEW_LINE DEDENT |
Count of all possible values of X such that A % X = B | Function to return the count of all possible values for x such that ( A % x ) = B ; Case 1 ; Case 2 ; Case 3 ; Find the number of divisors of x which are greater than b ; Driver code | def countX ( a , b ) : NEW_LINE INDENT if ( b > a ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT elif ( a == b ) : NEW_LINE INDENT return - 1 NEW_LINE DEDENT else : NEW_LINE INDENT x = a - b NEW_LINE ans = 0 NEW_LINE i = 1 NEW_LINE while i * i <= x : NEW_LINE INDENT if ( x % i == 0 ) : NEW_LINE INDENT d1 = i NEW_LINE d2 = b - 1 NEW_LINE if ( i * i != x ) : NEW_LINE INDENT d2 = x // i NEW_LINE DEDENT if ( d1 > b ) : NEW_LINE INDENT ans += 1 NEW_LINE DEDENT if ( d2 > b ) : NEW_LINE INDENT ans += 1 NEW_LINE DEDENT DEDENT i += 1 NEW_LINE DEDENT return ans NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT a = 21 NEW_LINE b = 5 NEW_LINE print ( countX ( a , b ) ) NEW_LINE DEDENT |
Find the Jaccard Index and Jaccard Distance between the two given sets | Function to return the intersection set of s1 and s2 ; Find the intersection of the two sets ; Function to return the Jaccard index of two sets ; Sizes of both the sets ; Get the intersection set ; Size of the intersection set ; Calculate the Jaccard index using the formula ; Return the Jaccard index ; Function to return the Jaccard distance ; Calculate the Jaccard distance using the formula ; Return the Jaccard distance ; Driver code ; Elements of the 1 st set ; Elements of the 2 nd set ; Print the Jaccard index and Jaccard distance | def intersection ( s1 , s2 ) : NEW_LINE INDENT intersect = s1 & s2 ; NEW_LINE return intersect ; NEW_LINE DEDENT def jaccard_index ( s1 , s2 ) : NEW_LINE INDENT size_s1 = len ( s1 ) ; NEW_LINE size_s2 = len ( s2 ) ; NEW_LINE intersect = intersection ( s1 , s2 ) ; NEW_LINE size_in = len ( intersect ) ; NEW_LINE jaccard_in = size_in / ( size_s1 + size_s2 - size_in ) ; NEW_LINE return jaccard_in ; NEW_LINE DEDENT def jaccard_distance ( jaccardIndex ) : NEW_LINE INDENT jaccard_dist = 1 - jaccardIndex ; NEW_LINE return jaccard_dist ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT s1 = set ( ) ; NEW_LINE s1 . add ( 1 ) ; NEW_LINE s1 . add ( 2 ) ; NEW_LINE s1 . add ( 3 ) ; NEW_LINE s1 . add ( 4 ) ; NEW_LINE s1 . add ( 5 ) ; NEW_LINE s2 = set ( ) ; NEW_LINE s2 . add ( 4 ) ; NEW_LINE s2 . add ( 5 ) ; NEW_LINE s2 . add ( 6 ) ; NEW_LINE s2 . add ( 7 ) ; NEW_LINE s2 . add ( 8 ) ; NEW_LINE s2 . add ( 9 ) ; NEW_LINE s2 . add ( 10 ) ; NEW_LINE jaccardIndex = jaccard_index ( s1 , s2 ) ; NEW_LINE print ( " Jaccard β index β = β " , jaccardIndex ) ; NEW_LINE print ( " Jaccard β distance β = β " , jaccard_distance ( jaccardIndex ) ) ; NEW_LINE DEDENT |
Find the sum of numbers from 1 to n excluding those which are powers of K | Function to return the sum of all the powers of k from the range [ 1 , n ] ; To store the sum of the series ; While current power of k <= n ; Add current power to the sum ; Next power of k ; Return the sum of the series ; Find to return the sum of the elements from the range [ 1 , n ] excluding those which are powers of k ; Sum of all the powers of k from [ 1 , n ] ; Sum of all the elements from [ 1 , n ] ; Return the required sum ; Driver code | def sumPowersK ( n , k ) : NEW_LINE INDENT sum = 0 ; num = 1 ; NEW_LINE while ( num <= n ) : NEW_LINE INDENT sum += num ; NEW_LINE num *= k ; NEW_LINE DEDENT return sum ; NEW_LINE DEDENT def getSum ( n , k ) : NEW_LINE INDENT pwrK = sumPowersK ( n , k ) ; NEW_LINE sumAll = ( n * ( n + 1 ) ) / 2 ; NEW_LINE return ( sumAll - pwrK ) ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT n = 10 ; k = 3 ; NEW_LINE print ( getSum ( n , k ) ) ; NEW_LINE DEDENT |
Maximum number of people that can be killed with strength P | Python3 implementation of the approach ; Function to return the maximum number of people that can be killed ; Loop will break when the ith person cannot be killed ; Driver code | from math import sqrt NEW_LINE def maxPeople ( p ) : NEW_LINE INDENT tmp = 0 ; count = 0 ; NEW_LINE for i in range ( 1 , int ( sqrt ( p ) ) + 1 ) : NEW_LINE INDENT tmp = tmp + ( i * i ) ; NEW_LINE if ( tmp <= p ) : NEW_LINE INDENT count += 1 ; NEW_LINE DEDENT else : NEW_LINE INDENT break ; NEW_LINE DEDENT DEDENT return count ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT p = 14 ; NEW_LINE print ( maxPeople ( p ) ) ; NEW_LINE DEDENT |
Maximum number of people that can be killed with strength P | Python3 implementation of the approach ; Function to return the maximum number of people that can be killed ; Storing the sum beforehand so that it can be used in each query ; lower_bound returns an iterator pointing to the first element greater than or equal to your val ; Previous value ; Returns the index in array upto which killing is possible with strength P ; Driver code | kN = 1000000 ; NEW_LINE def maxPeople ( p ) : NEW_LINE INDENT sums = [ 0 ] * kN ; NEW_LINE sums [ 0 ] = 0 ; NEW_LINE for i in range ( 1 , kN ) : NEW_LINE INDENT sums [ i ] = ( i * i ) + sums [ i - 1 ] ; NEW_LINE DEDENT it = lower_bound ( sums , 0 , kN , p ) ; NEW_LINE if ( it > p ) : NEW_LINE INDENT it -= 1 ; NEW_LINE DEDENT return it ; NEW_LINE DEDENT def lower_bound ( a , low , high , element ) : NEW_LINE INDENT while ( low < high ) : NEW_LINE INDENT middle = int ( low + ( high - low ) / 2 ) ; NEW_LINE if ( element > a [ middle ] ) : NEW_LINE INDENT low = middle + 1 ; NEW_LINE DEDENT else : NEW_LINE INDENT high = middle ; NEW_LINE DEDENT DEDENT return low ; NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT p = 14 ; NEW_LINE print ( maxPeople ( p ) ) ; NEW_LINE DEDENT |
Maximum number of people that can be killed with strength P | helper function which returns the sum of series ( 1 ^ 2 + 2 ^ 2 + ... + n ^ 2 ) ; maxPeople function which returns appropriate value using Binary Search in O ( logn ) ; Set the lower and higher values ; calculate the mid using low and high ; compare value with n ; return the ans | def squareSeries ( n ) : NEW_LINE INDENT return ( n * ( n + 1 ) * ( 2 * n + 1 ) ) // 6 NEW_LINE DEDENT def maxPeople ( n ) : NEW_LINE INDENT low = 0 NEW_LINE high = 1000000000000000 NEW_LINE while low <= high : NEW_LINE INDENT mid = low + ( ( high - low ) // 2 ) NEW_LINE value = squareSeries ( mid ) NEW_LINE if value <= n : NEW_LINE INDENT ans = mid NEW_LINE low = mid + 1 NEW_LINE DEDENT else : NEW_LINE INDENT high = mid - 1 NEW_LINE DEDENT DEDENT return ans NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT p = 14 NEW_LINE print ( maxPeople ( p ) ) NEW_LINE DEDENT |
Find the index which is the last to be reduced to zero after performing a given operation | Function that returns the index which will be the last to become zero after performing given operation ; Initialize the result ; Finding the ceil value of each index ; Finding the index with maximum ceil value ; Driver code | def findIndex ( a , n , k ) : NEW_LINE INDENT index = - 1 NEW_LINE max_ceil = - 10 ** 9 NEW_LINE for i in range ( n ) : NEW_LINE INDENT a [ i ] = ( a [ i ] + k - 1 ) // k NEW_LINE DEDENT for i in range ( n ) : NEW_LINE INDENT if ( a [ i ] >= max_ceil ) : NEW_LINE INDENT max_ceil = a [ i ] NEW_LINE index = i NEW_LINE DEDENT DEDENT return index NEW_LINE DEDENT arr = [ 31 , 12 , 25 , 27 , 32 , 19 ] NEW_LINE K = 5 NEW_LINE N = len ( arr ) NEW_LINE print ( findIndex ( arr , N , K ) ) NEW_LINE |
Queries to find the maximum Xor value between X and the nodes of a given level of a perfect binary tree | Python3 implementation of the approach ; Function to solve queries of the maximum xor value between the nodes in a given level L of a perfect binary tree and a given value X ; Initialize result ; Initialize array to store bits ; Initialize a copy of X and size of array ; Storing the bits of X in the array a [ ] ; Filling the array b [ ] ; Initializing variable which gives maximum xor ; Getting the maximum xor value ; Return the result ; Driver code ; Perform queries | MAXN = 60 NEW_LINE def solveQuery ( L , X ) : NEW_LINE INDENT res = 0 NEW_LINE a = [ 0 for i in range ( MAXN ) ] NEW_LINE b = [ 0 for i in range ( MAXN ) ] NEW_LINE ref = X NEW_LINE size_a = 0 NEW_LINE while ( ref > 0 ) : NEW_LINE INDENT a [ size_a ] = ref % 2 NEW_LINE ref //= 2 NEW_LINE size_a += 1 NEW_LINE DEDENT for i in range ( min ( size_a , L ) ) : NEW_LINE INDENT if ( a [ i ] == 1 ) : NEW_LINE INDENT b [ i ] = 0 NEW_LINE DEDENT else : NEW_LINE INDENT b [ i ] = 1 NEW_LINE DEDENT DEDENT for i in range ( min ( size_a , L ) , L ) : NEW_LINE INDENT b [ i ] = 1 NEW_LINE DEDENT b [ L - 1 ] = 1 NEW_LINE temp = 0 NEW_LINE p = 1 NEW_LINE for i in range ( L ) : NEW_LINE INDENT temp += b [ i ] * p NEW_LINE p *= 2 NEW_LINE DEDENT res = temp ^ X NEW_LINE return res NEW_LINE DEDENT queries = [ [ 2 , 5 ] , [ 3 , 15 ] ] NEW_LINE q = len ( queries ) NEW_LINE for i in range ( q ) : NEW_LINE INDENT print ( solveQuery ( queries [ i ] [ 0 ] , queries [ i ] [ 1 ] ) ) NEW_LINE DEDENT |
Count index pairs which satisfy the given condition | Function to return the count of required index pairs ; To store the required count ; Array to store the left elements upto which current element is maximum ; Iterating through the whole permutation except first and last element ; If current element can be maximum in a subsegment ; Current maximum ; Iterating for smaller values then current maximum on left of it ; Storing left borders of the current maximum ; Iterating for smaller values then current maximum on right of it ; Condition satisfies ; Return count of subsegments ; Driver Code | def Count_Segment ( p , n ) : NEW_LINE INDENT count = 0 NEW_LINE upto = [ False ] * ( n + 1 ) NEW_LINE for i in range ( 1 , n - 1 ) : NEW_LINE INDENT if p [ i ] > p [ i - 1 ] and p [ i ] > p [ i + 1 ] : NEW_LINE INDENT curr = p [ i ] NEW_LINE j = i - 1 NEW_LINE while j >= 0 and p [ j ] < curr : NEW_LINE INDENT upto [ p [ j ] ] = curr NEW_LINE j -= 1 NEW_LINE DEDENT j = i + 1 NEW_LINE while j < n and p [ j ] < curr : NEW_LINE INDENT if upto [ curr - p [ j ] ] == curr : NEW_LINE INDENT count += 1 NEW_LINE DEDENT j += 1 NEW_LINE DEDENT DEDENT DEDENT return count NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT p = [ 3 , 4 , 1 , 5 , 2 ] NEW_LINE n = len ( p ) NEW_LINE print ( Count_Segment ( p , n ) ) NEW_LINE DEDENT |
Check whether a number can be represented as sum of K distinct positive integers | Function that returns true if n can be represented as the sum of exactly k distinct positive integers ; If n can be represented as 1 + 2 + 3 + ... + ( k - 1 ) + ( k + x ) ; Driver code | def solve ( n , k ) : NEW_LINE INDENT if ( n >= ( k * ( k + 1 ) ) // 2 ) : NEW_LINE INDENT return True NEW_LINE DEDENT return False NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT n = 12 NEW_LINE k = 4 NEW_LINE if ( solve ( n , k ) ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT DEDENT |
Check whether product of integers from a to b is positive , negative or zero | Function to check whether the product of integers of the range [ a , b ] is positive , negative or zero ; If both a and b are positive then the product will be positive ; If a is negative and b is positive then the product will be zero ; If both a and b are negative then we have to find the count of integers in the range ; Total integers in the range ; If n is even then the resultant product is positive ; If n is odd then the resultant product is negative ; Driver code | def solve ( a , b ) : NEW_LINE INDENT if ( a > 0 and b > 0 ) : NEW_LINE INDENT print ( " Positive " ) NEW_LINE DEDENT elif ( a <= 0 and b >= 0 ) : NEW_LINE INDENT print ( " Zero " ) NEW_LINE DEDENT else : NEW_LINE INDENT n = abs ( a - b ) + 1 NEW_LINE if ( n % 2 == 0 ) : NEW_LINE INDENT print ( " Positive " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " Negative " ) NEW_LINE DEDENT DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT a = - 10 NEW_LINE b = - 2 NEW_LINE solve ( a , b ) NEW_LINE DEDENT |
Bitwise AND of sub | Function to return the minimum possible value of | K - X | where X is the bitwise AND of the elements of some sub - array ; Check all possible sub - arrays ; Find the overall minimum ; Driver code | def closetAND ( arr , n , k ) : NEW_LINE INDENT ans = 10 ** 9 NEW_LINE for i in range ( n ) : NEW_LINE INDENT X = arr [ i ] NEW_LINE for j in range ( i , n ) : NEW_LINE INDENT X &= arr [ j ] NEW_LINE ans = min ( ans , abs ( k - X ) ) NEW_LINE DEDENT DEDENT return ans NEW_LINE DEDENT arr = [ 4 , 7 , 10 ] NEW_LINE n = len ( arr ) NEW_LINE k = 2 ; NEW_LINE print ( closetAND ( arr , n , k ) ) NEW_LINE |
Program to find the rate percentage from compound interest of consecutive years | Function to return the required rate percentage ; Driver code | def Rate ( N1 , N2 ) : NEW_LINE INDENT rate = ( N2 - N1 ) * 100 // ( N1 ) ; NEW_LINE return rate NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT N1 = 100 NEW_LINE N2 = 120 NEW_LINE print ( Rate ( N1 , N2 ) , " β % " ) NEW_LINE DEDENT |
Find prime number K in an array such that ( A [ i ] % K ) is maximum | Python 3 implementation of the approach ; Function to return the required prime number from the array ; Find maximum value in the array ; USE SIEVE TO FIND ALL PRIME NUMBERS LESS THAN OR EQUAL TO max_val Create a boolean array " prime [ 0 . . n ] " . A value in prime [ i ] will finally be false if i is Not a prime , else true . ; Remaining part of SIEVE ; If prime [ p ] is not changed , then it is a prime ; Update all multiples of p ; To store the maximum prime number ; If current element is prime then update the maximum prime ; Return the maximum prime number from the array ; Driver code | from math import sqrt NEW_LINE def getPrime ( arr , n ) : NEW_LINE INDENT max_val = arr [ 0 ] NEW_LINE for i in range ( len ( arr ) ) : NEW_LINE INDENT if ( arr [ i ] > max_val ) : NEW_LINE INDENT max_val = arr [ i ] NEW_LINE DEDENT DEDENT prime = [ True for i in range ( max_val + 1 ) ] NEW_LINE prime [ 0 ] = False NEW_LINE prime [ 1 ] = False NEW_LINE for p in range ( 2 , int ( sqrt ( max_val ) ) + 1 , 1 ) : NEW_LINE INDENT if ( prime [ p ] == True ) : NEW_LINE INDENT for i in range ( p * 2 , max_val + 1 , p ) : NEW_LINE INDENT prime [ i ] = False NEW_LINE DEDENT DEDENT DEDENT maximum = - 1 NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( prime [ arr [ i ] ] ) : NEW_LINE INDENT maximum = max ( maximum , arr [ i ] ) NEW_LINE DEDENT DEDENT return maximum NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 2 , 10 , 15 , 7 , 6 , 8 , 13 ] NEW_LINE n = len ( arr ) NEW_LINE print ( getPrime ( arr , n ) ) NEW_LINE DEDENT |
Minimum integer such that it leaves a remainder 1 on dividing with any element from the range [ 2 , N ] | Python3 implementation of the approach ; Function to return the smallest number which on dividing with any element from the range [ 2 , N ] leaves a remainder of 1 ; Find the LCM of the elements from the range [ 2 , N ] ; Return the required number ; Driver code | from math import gcd NEW_LINE def getMinNum ( N ) : NEW_LINE INDENT lcm = 1 ; NEW_LINE for i in range ( 2 , N + 1 ) : NEW_LINE INDENT lcm = ( ( i * lcm ) // ( gcd ( i , lcm ) ) ) ; NEW_LINE DEDENT return ( lcm + 1 ) ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT N = 5 ; NEW_LINE print ( getMinNum ( N ) ) ; NEW_LINE DEDENT |
Maximum number of edges in Bipartite graph | Function to return the maximum number of edges possible in a Bipartite graph with N vertices ; Driver code | def maxEdges ( N ) : NEW_LINE INDENT edges = 0 ; NEW_LINE edges = ( N * N ) // 4 ; NEW_LINE return edges ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT N = 5 ; NEW_LINE print ( maxEdges ( N ) ) ; NEW_LINE DEDENT |
Check if the robot is within the bounds of the grid after given moves | Function that returns true if the robot is safe ; If current move is " L " then increase the counter of coll ; If value of coll is equal to column then break ; If current move is " R " then increase the counter of colr ; If value of colr is equal to column then break ; If current move is " U " then increase the counter of rowu ; If value of rowu is equal to row then break ; If current move is " D " then increase the counter of rowd ; If value of rowd is equal to row then break ; If robot is within the bounds of the grid ; Unsafe ; Driver code | def isSafe ( N , M , str ) : NEW_LINE INDENT coll = 0 NEW_LINE colr = 0 NEW_LINE rowu = 0 NEW_LINE rowd = 0 NEW_LINE for i in range ( len ( str ) ) : NEW_LINE INDENT if ( str [ i ] == ' L ' ) : NEW_LINE INDENT coll += 1 NEW_LINE if ( colr > 0 ) : NEW_LINE INDENT colr -= 1 NEW_LINE DEDENT if ( coll == M ) : NEW_LINE INDENT break NEW_LINE DEDENT DEDENT elif ( str [ i ] == ' R ' ) : NEW_LINE INDENT colr += 1 NEW_LINE if ( coll > 0 ) : NEW_LINE INDENT coll -= 1 NEW_LINE DEDENT if ( colr == M ) : NEW_LINE INDENT break NEW_LINE DEDENT DEDENT elif ( str [ i ] == ' U ' ) : NEW_LINE INDENT rowu += 1 NEW_LINE if ( rowd > 0 ) : NEW_LINE INDENT rowd -= 1 NEW_LINE DEDENT if ( rowu == N ) : NEW_LINE INDENT break NEW_LINE DEDENT DEDENT elif ( str [ i ] == ' D ' ) : NEW_LINE INDENT rowd += 1 NEW_LINE if ( rowu > 0 ) : NEW_LINE INDENT rowu -= 1 NEW_LINE DEDENT if ( rowd == N ) : NEW_LINE INDENT break NEW_LINE DEDENT DEDENT DEDENT if ( abs ( rowd ) < N and abs ( rowu ) < N and abs ( coll ) < M and abs ( colr ) < M ) : NEW_LINE INDENT return True NEW_LINE DEDENT return False NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 1 NEW_LINE M = 1 NEW_LINE str = " R " NEW_LINE if ( isSafe ( N , M , str ) ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT DEDENT |
Find sub | Function to print the valid indices in the array ; Function to find sub - arrays from two different arrays with equal sum ; Map to store the indices in A and B which produce the given difference ; Find the smallest j such that b [ j ] >= a [ i ] ; Difference encountered for the second time ; b [ j ] - a [ i ] = b [ idx . second ] - a [ idx . first ] b [ j ] - b [ idx . second ] = a [ i ] = a [ idx . first ] So sub - arrays are a [ idx . first + 1. . . i ] and b [ idx . second + 1. . . j ] ; Store the indices for difference in the map ; Utility function to calculate the cumulative sum of the array ; Driver code ; Function to update the arrays with their cumulative sum ; Swap is true as a and b are swapped during function call | def printAns ( x , y , num ) : NEW_LINE INDENT print ( " Indices β in β array " , num , " : " , end = " β " ) NEW_LINE for i in range ( x , y ) : NEW_LINE INDENT print ( i , end = " , β " ) NEW_LINE DEDENT print ( y ) NEW_LINE DEDENT def findSubarray ( N , a , b , swap ) : NEW_LINE INDENT index = { } NEW_LINE difference , j = 0 , 0 NEW_LINE index [ 0 ] = ( - 1 , - 1 ) NEW_LINE for i in range ( 0 , N ) : NEW_LINE INDENT while b [ j ] < a [ i ] : NEW_LINE INDENT j += 1 NEW_LINE DEDENT difference = b [ j ] - a [ i ] NEW_LINE if difference in index : NEW_LINE INDENT if swap : NEW_LINE INDENT idx = index [ b [ j ] - a [ i ] ] NEW_LINE printAns ( idx [ 1 ] + 1 , j , 1 ) NEW_LINE printAns ( idx [ 0 ] + 1 , i , 2 ) NEW_LINE DEDENT else : NEW_LINE INDENT idx = index [ b [ j ] - a [ i ] ] NEW_LINE printAns ( idx [ 0 ] + 1 , i , 1 ) NEW_LINE printAns ( idx [ 1 ] + 1 , j , 2 ) NEW_LINE DEDENT return NEW_LINE DEDENT index [ difference ] = ( i , j ) NEW_LINE DEDENT print ( " - 1" ) NEW_LINE DEDENT def cumulativeSum ( arr , n ) : NEW_LINE INDENT for i in range ( 1 , n ) : NEW_LINE INDENT arr [ i ] += arr [ i - 1 ] NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT a = [ 1 , 2 , 3 , 4 , 5 ] NEW_LINE b = [ 6 , 2 , 1 , 5 , 4 ] NEW_LINE N = len ( a ) NEW_LINE cumulativeSum ( a , N ) NEW_LINE cumulativeSum ( b , N ) NEW_LINE if b [ N - 1 ] > a [ N - 1 ] : NEW_LINE INDENT findSubarray ( N , a , b , False ) NEW_LINE DEDENT else : NEW_LINE INDENT findSubarray ( N , b , a , True ) NEW_LINE DEDENT DEDENT |
Find permutation of first N natural numbers that satisfies the given condition | Function to find permutation ( p ) of first N natural numbers such that there are exactly K elements of permutation such that GCD ( p [ i ] , i ) > 1 ; First place all the numbers in their respective places ; Modify for first n - k integers ; In first index place n - k ; Print the permutation ; Driver code | def Permutation ( n , k ) : NEW_LINE INDENT p = [ 0 for i in range ( n + 1 ) ] NEW_LINE for i in range ( 1 , n + 1 ) : NEW_LINE INDENT p [ i ] = i NEW_LINE DEDENT for i in range ( 1 , n - k ) : NEW_LINE INDENT p [ i + 1 ] = i NEW_LINE DEDENT p [ 1 ] = n - k NEW_LINE for i in range ( 1 , n + 1 ) : NEW_LINE INDENT print ( p [ i ] , end = " β " ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT n = 5 NEW_LINE k = 2 NEW_LINE Permutation ( n , k ) NEW_LINE DEDENT |
Count number of 1 s in the array after N moves | Function to count number of 1 's in the array after performing N moves ; If index is multiple of move number ; arr [ j - 1 ] = 1 Convert 0 to 1 ; arr [ j - 1 ] = 0 Convert 1 to 0 ; Count number of 1 's ; count += 1 count number of 1 's ; Driver Code ; Initialize all elements to 0 | def countOnes ( arr , N ) : NEW_LINE INDENT for i in range ( 1 , N + 1 , 1 ) : NEW_LINE INDENT for j in range ( i , N + 1 , 1 ) : NEW_LINE INDENT if ( j % i == 0 ) : NEW_LINE INDENT if ( arr [ j - 1 ] == 0 ) : NEW_LINE else : NEW_LINE DEDENT DEDENT DEDENT count = 0 NEW_LINE for i in range ( N ) : NEW_LINE INDENT if ( arr [ i ] == 1 ) : NEW_LINE DEDENT return count NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 0 for i in range ( 10 ) ] NEW_LINE ans = countOnes ( arr , N ) NEW_LINE print ( ans ) NEW_LINE DEDENT |
Number of positions such that adding K to the element is greater than sum of all other elements | Function that will find out the valid position ; find sum of all the elements ; adding K to the element and check whether it is greater than sum of all other elements ; Driver code | def validPosition ( arr , N , K ) : NEW_LINE INDENT count = 0 ; sum = 0 ; NEW_LINE for i in range ( N ) : NEW_LINE INDENT sum += arr [ i ] ; NEW_LINE DEDENT for i in range ( N ) : NEW_LINE INDENT if ( ( arr [ i ] + K ) > ( sum - arr [ i ] ) ) : NEW_LINE INDENT count += 1 ; NEW_LINE DEDENT DEDENT return count ; NEW_LINE DEDENT arr = [ 2 , 1 , 6 , 7 ] ; NEW_LINE K = 4 ; NEW_LINE N = len ( arr ) ; NEW_LINE print ( validPosition ( arr , N , K ) ) ; NEW_LINE |
Count unique numbers that can be generated from N by adding one and removing trailing zeros | Function to count the unique numbers ; If the number has already been visited ; Insert the number to the set ; First step ; Second step remove trailing zeros ; Recur again for the new number ; Driver code | def count_unique ( s , n ) : NEW_LINE INDENT if ( s . count ( n ) ) : NEW_LINE INDENT return ; NEW_LINE DEDENT s . append ( n ) ; NEW_LINE n += 1 ; NEW_LINE while ( n % 10 == 0 ) : NEW_LINE INDENT n = n // 10 ; NEW_LINE DEDENT count_unique ( s , n ) ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT n = 10 NEW_LINE s = [ ] NEW_LINE count_unique ( s , n ) NEW_LINE print ( len ( s ) ) NEW_LINE DEDENT |
Find element with the maximum set bits in an array | Function to return the element from the array which has the maximum set bits ; To store the required element and the maximum set bits so far ; Count of set bits in the current element ; Update the max ; Driver code | def maxBitElement ( arr , n ) : NEW_LINE INDENT num = 0 NEW_LINE max = - 1 NEW_LINE for i in range ( n ) : NEW_LINE INDENT cnt = bin ( arr [ i ] ) . count ( '1' ) NEW_LINE if ( cnt > max ) : NEW_LINE INDENT max = cnt NEW_LINE num = arr [ i ] NEW_LINE DEDENT DEDENT return num NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 3 , 2 , 4 , 7 , 1 , 10 , 5 , 8 , 9 , 6 ] NEW_LINE n = len ( arr ) NEW_LINE print ( maxBitElement ( arr , n ) ) NEW_LINE DEDENT |
Count pairs with average present in the same array | Python 3 implementation of the approach ; Function to return the count of valid pairs ; Frequency array Twice the original size to hold negative elements as well ; Update the frequency of each of the array element ; If say x = - 1000 then we will place the frequency of - 1000 at ( - 1000 + 1000 = 0 ) a [ 0 ] index ; To store the count of valid pairs ; Remember we will check only for ( even , even ) or ( odd , odd ) pairs of indexes as the average of two consecutive elements is a floating point number ; Driver code | N = 1000 NEW_LINE def countPairs ( arr , n ) : NEW_LINE INDENT size = ( 2 * N ) + 1 NEW_LINE freq = [ 0 for i in range ( size ) ] NEW_LINE for i in range ( n ) : NEW_LINE INDENT x = arr [ i ] NEW_LINE freq [ x + N ] += 1 NEW_LINE DEDENT ans = 0 NEW_LINE for i in range ( size ) : NEW_LINE INDENT if ( freq [ i ] > 0 ) : NEW_LINE INDENT ans += int ( ( ( freq [ i ] ) * ( freq [ i ] - 1 ) ) / 2 ) NEW_LINE for j in range ( i + 2 , 2001 , 2 ) : NEW_LINE INDENT if ( freq [ j ] > 0 and ( freq [ int ( ( i + j ) / 2 ) ] > 0 ) ) : NEW_LINE INDENT ans += ( freq [ i ] * freq [ j ] ) NEW_LINE DEDENT DEDENT DEDENT DEDENT return ans NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 4 , 2 , 5 , 1 , 3 , 5 ] NEW_LINE n = len ( arr ) NEW_LINE print ( countPairs ( arr , n ) ) NEW_LINE DEDENT |
Smallest and Largest sum of two n | Function to return the smallest sum of 2 n - digit numbers ; Function to return the largest sum of 2 n - digit numbers ; Driver code | def smallestSum ( n ) : NEW_LINE INDENT if ( n == 1 ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT return ( 2 * pow ( 10 , n - 1 ) ) NEW_LINE DEDENT def largestSum ( n ) : NEW_LINE INDENT return ( 2 * ( pow ( 10 , n ) - 1 ) ) NEW_LINE DEDENT n = 4 NEW_LINE print ( " Largest β = β " , largestSum ( n ) ) NEW_LINE print ( " Smallest β = β " , smallestSum ( n ) ) NEW_LINE |
Given two arrays count all pairs whose sum is an odd number | Function that returns the number of pairs ; Count of odd and even numbers ; Traverse in the first array and count the number of odd and evene numbers in them ; Traverse in the second array and count the number of odd and evene numbers in them ; Count the number of pairs ; Return the number of pairs ; Driver code | def count_pairs ( a , b , n , m ) : NEW_LINE INDENT odd1 = 0 NEW_LINE even1 = 0 NEW_LINE odd2 = 0 NEW_LINE even2 = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( a [ i ] % 2 ) : NEW_LINE INDENT odd1 += 1 NEW_LINE DEDENT else : NEW_LINE INDENT even1 += 1 NEW_LINE DEDENT DEDENT for i in range ( m ) : NEW_LINE INDENT if ( b [ i ] % 2 ) : NEW_LINE INDENT odd2 += 1 NEW_LINE DEDENT else : NEW_LINE INDENT even2 += 1 NEW_LINE DEDENT DEDENT pairs = ( min ( odd1 , even2 ) + min ( odd2 , even1 ) ) NEW_LINE return pairs NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT a = [ 9 , 14 , 6 , 2 , 11 ] NEW_LINE b = [ 8 , 4 , 7 , 20 ] NEW_LINE n = len ( a ) NEW_LINE m = len ( b ) NEW_LINE print ( count_pairs ( a , b , n , m ) ) NEW_LINE DEDENT |
Print steps to make a number in form of 2 ^ X | Function to find the leftmost unset bit in a number . ; Function that perform the step ; Find the leftmost unset bit ; If the number has no bit unset , it means it is in form 2 ^ x - 1 ; Count the steps ; Iterate till number is of form 2 ^ x - 1 ; At even step increase by 1 ; Odd step xor with any 2 ^ m - 1 ; Find the leftmost unset bit ; 2 ^ m - 1 ; Perform the step ; Increase the steps ; Driver code | def find_leftmost_unsetbit ( n ) : NEW_LINE INDENT ind = - 1 ; NEW_LINE i = 1 ; NEW_LINE while ( n ) : NEW_LINE INDENT if ( ( n % 2 ) != 1 ) : NEW_LINE INDENT ind = i ; NEW_LINE DEDENT i += 1 ; NEW_LINE n >>= 1 ; NEW_LINE DEDENT return ind ; NEW_LINE DEDENT def perform_steps ( n ) : NEW_LINE INDENT left = find_leftmost_unsetbit ( n ) ; NEW_LINE if ( left == - 1 ) : NEW_LINE INDENT print ( " No β steps β required " ) ; NEW_LINE return ; NEW_LINE DEDENT step = 1 ; NEW_LINE while ( find_leftmost_unsetbit ( n ) != - 1 ) : NEW_LINE INDENT if ( step % 2 == 0 ) : NEW_LINE INDENT n += 1 ; NEW_LINE print ( " Step " , step , " : Increase by 1 " ) ; NEW_LINE DEDENT else : NEW_LINE INDENT m = find_leftmost_unsetbit ( n ) ; NEW_LINE num = ( 2 ** m ) - 1 ; NEW_LINE n = n ^ num ; NEW_LINE print ( " Step " , step , " : β Xor β with " , num ) ; NEW_LINE DEDENT step += 1 ; NEW_LINE DEDENT DEDENT n = 39 ; NEW_LINE perform_steps ( n ) ; NEW_LINE |
Determine the position of the third person on regular N sided polygon | Function to find out the number of that vertices ; Another person can 't stand on vertex on which 2 children stand. ; calculating minimum jumps from each vertex . ; Calculate Sum of jumps . ; Driver code ; Calling function | def vertices ( N , A , B ) : NEW_LINE INDENT position = 0 NEW_LINE miniSum = 10 ** 9 NEW_LINE Sum = 0 NEW_LINE for i in range ( 1 , N + 1 ) : NEW_LINE INDENT if ( i == A or i == B ) : NEW_LINE INDENT continue NEW_LINE DEDENT else : NEW_LINE INDENT x = abs ( i - A ) NEW_LINE y = abs ( i - B ) NEW_LINE Sum = x + y NEW_LINE if ( Sum < miniSum ) : NEW_LINE INDENT miniSum = Sum NEW_LINE position = i NEW_LINE DEDENT DEDENT DEDENT return position NEW_LINE DEDENT N = 3 NEW_LINE A = 1 NEW_LINE B = 2 NEW_LINE print ( " Vertex β = β " , vertices ( N , A , B ) ) NEW_LINE |
Find sum of factorials in an array | Function to return the factorial of n ; Function to return the sum of factorials of the array elements ; To store the required sum ; Add factorial of all the elements ; Driver code | def factorial ( n ) : NEW_LINE INDENT f = 1 ; NEW_LINE for i in range ( 1 , n + 1 ) : NEW_LINE INDENT f *= i ; NEW_LINE DEDENT return f ; NEW_LINE DEDENT def sumFactorial ( arr , n ) : NEW_LINE INDENT s = 0 ; NEW_LINE for i in range ( 0 , n ) : NEW_LINE INDENT s += factorial ( arr [ i ] ) ; NEW_LINE DEDENT return s ; NEW_LINE DEDENT arr = [ 7 , 3 , 5 , 4 , 8 ] ; NEW_LINE n = len ( arr ) ; NEW_LINE print ( sumFactorial ( arr , n ) ) ; NEW_LINE |
Minimum steps to color the tree with given colors | To store the required answer ; To store the graph ; Function to add edges ; Dfs function ; When there is difference in colors ; For all it 's child nodes ; Here zero is for parent of node 1 ; Adding edges in the graph ; Dfs call ; Required answer | ans = 0 NEW_LINE gr = [ [ ] for i in range ( 100005 ) ] NEW_LINE def Add_Edge ( u , v ) : NEW_LINE INDENT gr [ u ] . append ( v ) NEW_LINE gr [ v ] . append ( u ) NEW_LINE DEDENT def dfs ( child , par , color ) : NEW_LINE INDENT global ans NEW_LINE if ( color [ child ] != color [ par ] ) : NEW_LINE INDENT ans += 1 NEW_LINE DEDENT for it in gr [ child ] : NEW_LINE INDENT if ( it == par ) : NEW_LINE INDENT continue NEW_LINE DEDENT dfs ( it , child , color ) NEW_LINE DEDENT DEDENT color = [ 0 , 1 , 2 , 3 , 2 , 2 , 3 ] NEW_LINE Add_Edge ( 1 , 2 ) NEW_LINE Add_Edge ( 1 , 3 ) NEW_LINE Add_Edge ( 2 , 4 ) NEW_LINE Add_Edge ( 2 , 5 ) NEW_LINE Add_Edge ( 3 , 6 ) NEW_LINE dfs ( 1 , 0 , color ) NEW_LINE print ( ans ) NEW_LINE |
Subsets and Splits