text
stringlengths 17
3.65k
| code
stringlengths 70
5.84k
|
---|---|
Check if a string is a scrambled form of another string | Declaring unordered map globally ; Python3 program to check if a given string is a scrambled form of another string ; Strings of non - equal length cant ' be scramble strings ; Empty strings are scramble strings ; Equal strings are scramble strings ; Check for the condition of anagram ; ; Checking if both Substrings are in map or are already calculated or not ; Declaring a flag variable ; Check if S2 [ 0. . . i ] is a scrambled string of S1 [ 0. . . i ] and if S2 [ i + 1. . . n ] is a scrambled string of S1 [ i + 1. . . n ] ; Check if S2 [ 0. . . i ] is a scrambled string of S1 [ n - i ... n ] and S2 [ i + 1. . . n ] is a scramble string of S1 [ 0. . . n - i - 1 ] ; Storing calculated value to map ; If none of the above conditions are satisfied ; Driver Code | map = { } NEW_LINE def isScramble ( S1 : str , S2 : str ) : NEW_LINE INDENT if len ( S1 ) != len ( S2 ) : NEW_LINE INDENT return False NEW_LINE DEDENT n = len ( S1 ) NEW_LINE if not n : NEW_LINE INDENT return True NEW_LINE DEDENT if S1 == S2 : NEW_LINE INDENT return True NEW_LINE DEDENT if sorted ( S1 ) != sorted ( S2 ) : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT / * make key of type string for search in map * / NEW_LINE INDENT if ( S1 + ' β ' + S2 in map ) : NEW_LINE INDENT return map [ S1 + ' β ' + S2 ] NEW_LINE DEDENT flag = False NEW_LINE for i in range ( 1 , n ) : NEW_LINE INDENT if ( isScramble ( S1 [ : i ] , S2 [ : i ] ) and isScramble ( S1 [ i : ] , S2 [ i : ] ) ) : NEW_LINE INDENT flag = True NEW_LINE return True NEW_LINE DEDENT if ( isScramble ( S1 [ - i : ] , S2 [ : i ] ) and isScramble ( S1 [ : - i ] , S2 [ i : ] ) ) : NEW_LINE INDENT flag = True NEW_LINE return True NEW_LINE DEDENT DEDENT map [ S1 + " β " + S2 ] = flag NEW_LINE return False NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT S1 = " great " NEW_LINE S2 = " rgate " NEW_LINE if ( isScramble ( S1 , S2 ) ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT DEDENT |
Print the longest palindromic prefix of a given string | Function to find the longest prefix which is palindrome ; Find the length of the given string ; For storing the length of longest Prefix Palindrome ; Loop to check the substring of all length from 1 to n which is palindrome ; String of length i ; To store the value of temp ; Reversing the value of temp ; If string temp is palindromic then update the length ; Print the palindromic string of max_len ; Driver code ; Function call | def LongestPalindromicPrefix ( string ) : NEW_LINE INDENT n = len ( string ) NEW_LINE max_len = 0 NEW_LINE for length in range ( 0 , n + 1 ) : NEW_LINE INDENT temp = string [ 0 : length ] NEW_LINE temp2 = temp NEW_LINE temp3 = temp2 [ : : - 1 ] NEW_LINE if temp == temp3 : NEW_LINE INDENT max_len = length NEW_LINE DEDENT DEDENT print ( string [ 0 : max_len ] ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT string = " abaac " ; NEW_LINE LongestPalindromicPrefix ( string ) NEW_LINE DEDENT |
Minimum operations to make product of adjacent element pair of prefix sum negative | Function to find minimum operations needed to make the product of any two adjacent elements in prefix sum array negative ; Stores the minimum operations ; Stores the prefix sum and number of operations ; Traverse the array ; Update the value of sum ; Check if i + r is odd ; Check if prefix sum is not positive ; Update the value of ans and sum ; Check if prefix sum is not negative ; Update the value of ans and sum ; Update the value of res ; Print the value of res ; Driver code | def minOperations ( a ) : NEW_LINE INDENT res = 100000000000 NEW_LINE N = len ( a ) NEW_LINE for r in range ( 0 , 2 ) : NEW_LINE INDENT sum = 0 NEW_LINE ans = 0 NEW_LINE for i in range ( 0 , N ) : NEW_LINE INDENT sum += a [ i ] NEW_LINE if ( ( i + r ) % 2 ) : NEW_LINE INDENT if ( sum <= 0 ) : NEW_LINE INDENT ans += - sum + 1 NEW_LINE sum = 1 NEW_LINE DEDENT DEDENT else : NEW_LINE INDENT if ( sum >= 0 ) : NEW_LINE INDENT ans += sum + 1 ; NEW_LINE sum = - 1 ; NEW_LINE DEDENT DEDENT DEDENT res = min ( res , ans ) NEW_LINE DEDENT print ( res ) NEW_LINE DEDENT a = [ 1 , - 3 , 1 , 0 ] NEW_LINE minOperations ( a ) ; NEW_LINE |
K | Python program to find the K - th lexicographical string of length N ; Initialize the array to store the base 26 representation of K with all zeroes , that is , the initial string consists of N a 's ; Start filling all the N slots for the base 26 representation of K ; Store the remainder ; Reduce K ; If K is greater than the possible number of strings that can be represented by a string of length N ; Store the Kth lexicographical string ; Driver Code ; Reducing k value by 1 because our stored value starts from 0 | def find_kth_string_of_n ( n , k ) : NEW_LINE INDENT d = [ 0 for i in range ( n ) ] NEW_LINE for i in range ( n - 1 , - 1 , - 1 ) : NEW_LINE INDENT d [ i ] = k % 26 NEW_LINE k //= 26 NEW_LINE DEDENT if k > 0 : NEW_LINE INDENT return - 1 NEW_LINE DEDENT s = " " NEW_LINE for i in range ( n ) : NEW_LINE INDENT s += chr ( d [ i ] + ord ( ' a ' ) ) NEW_LINE DEDENT return s NEW_LINE DEDENT n = 3 NEW_LINE k = 10 NEW_LINE k -= 1 NEW_LINE print ( find_kth_string_of_n ( n , k ) ) NEW_LINE |
Length of the smallest substring which contains all vowels | Python3 program to find the length of the smallest substring of which contains all vowels ; Map to store the frequency of vowels ; Store the indices which contains the vowels ; If all vowels are not present in the string ; If the frequency of the vowel at i - th index exceeds 1 ; Decrease the frequency of that vowel ; Move to the left ; Otherwise set flag1 ; If the frequency of the vowel at j - th index exceeds 1 ; Decrease the frequency of that vowel ; Move to the right ; Otherwise set flag2 ; If both flag1 and flag2 are set , break out of the loop as the substring length cannot be minimized ; Return the length of the substring ; Driver Code | from collections import defaultdict NEW_LINE def findMinLength ( s ) : NEW_LINE INDENT n = len ( s ) NEW_LINE counts = defaultdict ( int ) NEW_LINE indices = [ ] NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( s [ i ] == ' a ' or s [ i ] == ' e ' or s [ i ] == ' o ' or s [ i ] == ' i ' or s [ i ] == ' u ' ) : NEW_LINE INDENT counts [ s [ i ] ] += 1 NEW_LINE indices . append ( i ) NEW_LINE DEDENT DEDENT if len ( counts ) < 5 : NEW_LINE INDENT return - 1 NEW_LINE DEDENT flag1 = 0 NEW_LINE flag2 = 0 NEW_LINE i = 0 NEW_LINE j = len ( indices ) - 1 NEW_LINE while ( j - i ) >= 4 : NEW_LINE INDENT if ( ~ flag1 and counts [ s [ indices [ i ] ] ] > 1 ) : NEW_LINE INDENT counts [ s [ indices [ i ] ] ] -= 1 NEW_LINE i += 1 NEW_LINE DEDENT else : NEW_LINE INDENT flag1 = 1 NEW_LINE DEDENT if ( ~ flag2 and counts [ s [ indices [ j ] ] ] > 1 ) : NEW_LINE INDENT counts [ s [ indices [ j ] ] ] -= 1 NEW_LINE j -= 1 NEW_LINE DEDENT else : NEW_LINE INDENT flag2 = 1 NEW_LINE DEDENT if ( flag1 and flag2 ) : NEW_LINE INDENT break NEW_LINE DEDENT DEDENT return ( indices [ j ] - indices [ i ] + 1 ) NEW_LINE DEDENT s = " aaeebbeaccaaoiuooooooooiuu " NEW_LINE print ( findMinLength ( s ) ) NEW_LINE |
Longest Subsequence of a String containing only Consonants | Returns true if x is consonants . ; '' Function to check whether a character is consonants or not ; Function to find the longest subsequence which contain all consonants ; Driver code ; Function call | def isComsomamts ( x ) : NEW_LINE INDENT x = x . lower ( ) NEW_LINE return not ( x == ' a ' or x == ' e ' or x == ' i ' or x == ' o ' or x == ' u ' ) NEW_LINE DEDENT def longestConsonantsSubsequence ( s ) : NEW_LINE INDENT answer = ' ' NEW_LINE n = len ( s ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT if isComsomamts ( s [ i ] ) : NEW_LINE INDENT answer += s [ i ] NEW_LINE DEDENT DEDENT return answer NEW_LINE DEDENT s = ' geeksforgeeks ' NEW_LINE print ( longestConsonantsSubsequence ( s ) ) NEW_LINE |
Find the length of the longest subsequence with first K alphabets having same frequency | Python3 program to find the longest subsequence with first K alphabets having same frequency ; Function to return the length of the longest subsequence with first K alphabets having same frequency ; Map to store frequency of all characters in the string ; Variable to store the frequency of the least frequent of first K alphabets ; Driver code | from collections import defaultdict NEW_LINE def lengthOfSubsequence ( st , K ) : NEW_LINE INDENT mp = defaultdict ( int ) NEW_LINE for ch in st : NEW_LINE INDENT mp [ ch ] += 1 NEW_LINE DEDENT minimum = mp [ ' A ' ] NEW_LINE for i in range ( 1 , K ) : NEW_LINE INDENT minimum = min ( minimum , mp [ chr ( i + ord ( ' A ' ) ) ] ) NEW_LINE DEDENT return ( minimum * K ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT st = " ACAABCCAB " NEW_LINE K = 3 NEW_LINE print ( lengthOfSubsequence ( st , K ) ) NEW_LINE DEDENT |
Detecting negative cycle using Floyd Warshall | Number of vertices in the graph ; Define Infinite as a large enough value . This value will be used for vertices not connected to each other ; Returns true if graph has negative weight cycle else false . ; dist [ ] [ ] will be the output matrix that will finally have the shortest distances between every pair of vertices ; Initialize the solution matrix same as input graph matrix . Or we can say the initial values of shortest distances are based on shortest paths considering no intermediate vertex . ; Add all vertices one by one to the set of intermediate vertices . -- -> Before start of a iteration , we have shortest distances between all pairs of vertices such that the shortest distances consider only the vertices in set { 0 , 1 , 2 , . . k - 1 } as intermediate vertices . -- -- > After the end of a iteration , vertex no . k is added to the set of intermediate vertices and the set becomes { 0 , 1 , 2 , . . k } ; Pick all vertices as source one by one ; Pick all vertices as destination for the above picked source ; If vertex k is on the shortest path from i to j , then update the value of dist [ i ] [ j ] ; If distance of any vertex from itself becomes negative , then there is a negative weight cycle . ; Let us create the following weighted graph 1 ( 0 ) -- -- -- -- -- -> ( 1 ) / | \ | | | - 1 | | - 1 | \ | / ( 3 ) < -- -- -- -- -- - ( 2 ) - 1 | V = 4 NEW_LINE INF = 99999 NEW_LINE def negCyclefloydWarshall ( graph ) : NEW_LINE INDENT dist = [ [ 0 for i in range ( V + 1 ) ] for j in range ( V + 1 ) ] NEW_LINE for i in range ( V ) : NEW_LINE INDENT for j in range ( V ) : NEW_LINE INDENT dist [ i ] [ j ] = graph [ i ] [ j ] NEW_LINE DEDENT DEDENT for k in range ( V ) : NEW_LINE INDENT for i in range ( V ) : NEW_LINE INDENT for j in range ( V ) : NEW_LINE INDENT if ( dist [ i ] [ k ] + dist [ k ] [ j ] < dist [ i ] [ j ] ) : NEW_LINE INDENT dist [ i ] [ j ] = dist [ i ] [ k ] + dist [ k ] [ j ] NEW_LINE DEDENT DEDENT DEDENT DEDENT for i in range ( V ) : NEW_LINE INDENT if ( dist [ i ] [ i ] < 0 ) : NEW_LINE INDENT return True NEW_LINE DEDENT DEDENT return False NEW_LINE DEDENT graph = [ [ 0 , 1 , INF , INF ] , [ INF , 0 , - 1 , INF ] , [ INF , INF , 0 , - 1 ] , [ - 1 , INF , INF , 0 ] ] NEW_LINE if ( negCyclefloydWarshall ( graph ) ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT |
Digital Root of a given large integer using Recursion | Function to convert given sum into string ; Loop to extract digit one by one from the given sum and concatenate into the string ; Type casting for concatenation ; Return converted string ; Function to get individual digit sum from string ; Loop to get individual digit sum ; Function call to convert sum into string ; Function to calculate the digital root of a very large number ; Base condition ; Function call to get individual digit sum ; Recursive function to get digital root of a very large number ; Driver code ; Function to print final digit | def convertToString ( sum ) : NEW_LINE INDENT str1 = " " NEW_LINE while ( sum ) : NEW_LINE INDENT str1 = str1 + chr ( ( sum % 10 ) + ord ( '0' ) ) NEW_LINE sum = sum // 10 NEW_LINE DEDENT return str1 NEW_LINE DEDENT def GetIndividulaDigitSum ( str1 , len1 ) : NEW_LINE INDENT sum = 0 NEW_LINE for i in range ( len1 ) : NEW_LINE INDENT sum = sum + ord ( str1 [ i ] ) - ord ( '0' ) NEW_LINE DEDENT return convertToString ( sum ) NEW_LINE DEDENT def GetDigitalRoot ( str1 ) : NEW_LINE INDENT if ( len ( str1 ) == 1 ) : NEW_LINE INDENT return ord ( str1 [ 0 ] ) - ord ( '0' ) NEW_LINE DEDENT str1 = GetIndividulaDigitSum ( str1 , len ( str1 ) ) NEW_LINE return GetDigitalRoot ( str1 ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT str1 = "675987890789756545689070986776987" NEW_LINE print ( GetDigitalRoot ( str1 ) ) NEW_LINE DEDENT |
Count the Number of matching characters in a pair of strings | Function to count the matching characters ; Traverse the string 1 char by char ; This will check if str1 [ i ] is present in str2 or not str2 . find ( str1 [ i ] ) returns - 1 if not found otherwise it returns the starting occurrence index of that character in str2 ; Driver code | def count ( str1 , str2 ) : NEW_LINE INDENT c = 0 ; j = 0 ; NEW_LINE for i in range ( len ( str1 ) ) : NEW_LINE INDENT if str1 [ i ] in str2 : NEW_LINE INDENT c += 1 ; NEW_LINE DEDENT j += 1 ; NEW_LINE DEDENT print ( " No . β of β matching β characters β are : β " , c ) ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT str1 = " aabcddekll12 @ " ; NEW_LINE str2 = " bb2211@55k " ; NEW_LINE count ( str1 , str2 ) ; NEW_LINE DEDENT |
Check if count of Alphabets and count of Numbers are equal in the given String | Function to count the number of alphabets ; Counter to store the number of alphabets in the string ; Every character in the string is iterated ; To check if the character is an alphabet or not ; Function to count the number of numbers ; Counter to store the number of alphabets in the string ; Every character in the string is iterated ; To check if the character is a digit or not ; Function to check if the count of alphabets is equal to the count of numbers or not ; Driver code | def countOfLetters ( string ) : NEW_LINE INDENT letter = 0 ; NEW_LINE for i in range ( len ( string ) ) : NEW_LINE INDENT if ( ( string [ i ] >= ' A ' and string [ i ] <= ' Z ' ) or ( string [ i ] >= ' a ' and string [ i ] <= ' z ' ) ) : NEW_LINE INDENT letter += 1 ; NEW_LINE DEDENT DEDENT return letter ; NEW_LINE DEDENT def countOfNumbers ( string ) : NEW_LINE INDENT number = 0 ; NEW_LINE for i in range ( len ( string ) ) : NEW_LINE INDENT if ( string [ i ] >= '0' and string [ i ] <= '9' ) : NEW_LINE INDENT number += 1 ; NEW_LINE DEDENT DEDENT return number ; NEW_LINE DEDENT def check ( string ) : NEW_LINE INDENT if ( countOfLetters ( string ) == countOfNumbers ( string ) ) : NEW_LINE INDENT print ( " Yes " ) ; NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) ; NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT string = " GeeKs01324" ; NEW_LINE check ( string ) ; NEW_LINE DEDENT |
Check if there is a cycle with odd weight sum in an undirected graph | This function returns true if the current subpart of the forest is two colorable , else false . ; Assign first color to source ; Create a queue ( FIFO ) of vertex numbers and enqueue source vertex for BFS traversal ; Run while there are vertices in queue ( Similar to BFS ) ; Find all non - colored adjacent vertices ; An edge from u to v exists and destination v is not colored ; Assign alternate color to this adjacent v of u ; An edge from u to v exists and destination v is colored with same color as u ; This function returns true if graph G [ V ] [ V ] is two colorable , else false ; Create a color array to store colors assigned to all veritces . Vertex number is used as index in this array . The value ' - 1' of colorArr [ i ] is used to indicate that no color is assigned to vertex ' i ' . The value 1 is used to indicate first color is assigned and value 0 indicates second color is assigned . ; As we are dealing with graph , the input might come as a forest , thus start coloring from a node and if true is returned we 'll know that we successfully colored the subpart of our forest and we start coloring again from a new uncolored node. This way we cover the entire forest. ; Returns false if an odd cycle is present else true int info [ ] [ ] is the information about our graph int n is the number of nodes int m is the number of informations given to us ; Declaring adjacency list of a graph Here at max , we can encounter all the edges with even weight thus there will be 1 pseudo node for each edge ; For odd weight edges , we directly add it in our graph ; For even weight edges , we break it ; Entering a pseudo node between u -- - v ; Keeping a record of number of pseudo nodes inserted ; Making a new pseudo node for next time ; We pass number graph G [ ] [ ] and total number of node = actual number of nodes + number of pseudo nodes added . ; Driver function ; ' n ' correspond to number of nodes in our graph while ' m ' correspond to the number of information about this graph . ; This function break the even weighted edges in two parts . Makes the adjacency representation of the graph and sends it for two coloring . | def twoColorUtil ( G , src , N , colorArr ) : NEW_LINE INDENT colorArr [ src ] = 1 NEW_LINE q = [ src ] NEW_LINE while len ( q ) > 0 : NEW_LINE INDENT u = q . pop ( 0 ) NEW_LINE for v in range ( 0 , len ( G [ u ] ) ) : NEW_LINE INDENT if colorArr [ G [ u ] [ v ] ] == - 1 : NEW_LINE INDENT colorArr [ G [ u ] [ v ] ] = 1 - colorArr [ u ] NEW_LINE q . append ( G [ u ] [ v ] ) NEW_LINE DEDENT elif colorArr [ G [ u ] [ v ] ] == colorArr [ u ] : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT DEDENT return True NEW_LINE DEDENT def twoColor ( G , N ) : NEW_LINE INDENT colorArr = [ - 1 ] * N NEW_LINE for i in range ( N ) : NEW_LINE INDENT if colorArr [ i ] == - 1 : NEW_LINE INDENT if twoColorUtil ( G , i , N , colorArr ) == False : NEW_LINE INDENT return False NEW_LINE DEDENT return True NEW_LINE DEDENT DEDENT DEDENT def isOddSum ( info , n , m ) : NEW_LINE INDENT G = [ [ ] for i in range ( 2 * n ) ] NEW_LINE pseudo , pseudo_count = n + 1 , 0 NEW_LINE for i in range ( 0 , m ) : NEW_LINE INDENT if info [ i ] [ 2 ] % 2 == 1 : NEW_LINE INDENT u , v = info [ i ] [ 0 ] , info [ i ] [ 1 ] NEW_LINE G [ u ] . append ( v ) NEW_LINE G [ v ] . append ( u ) NEW_LINE DEDENT else : NEW_LINE INDENT u , v = info [ i ] [ 0 ] , info [ i ] [ 1 ] NEW_LINE G [ u ] . append ( pseudo ) NEW_LINE G [ pseudo ] . append ( u ) NEW_LINE G [ v ] . append ( pseudo ) NEW_LINE G [ pseudo ] . append ( v ) NEW_LINE pseudo_count += 1 NEW_LINE pseudo += 1 NEW_LINE DEDENT DEDENT return twoColor ( G , n + pseudo_count ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT n , m = 4 , 3 NEW_LINE info = [ [ 1 , 2 , 12 ] , [ 2 , 3 , 1 ] , [ 4 , 3 , 1 ] , [ 4 , 1 , 20 ] ] NEW_LINE if isOddSum ( info , n , m ) == True : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT DEDENT |
Index of character depending on frequency count in string | Python3 implementation of the approach ; Function to perform the queries ; L [ i ] [ j ] stores the largest i such that ith character appears exactly jth times in str [ 0. . . i ] ; F [ i ] [ j ] stores the smallest i such that ith character appears exactly jth times in str [ 0. . . i ] ; To store the frequency of each of the character of str ; Current character of str ; Update its frequency ; For every lowercase character of the English alphabet ; If it is equal to the character under consideration then update L [ ] [ ] and R [ ] [ ] as it is cnt [ j ] th occurrence of character k ; Only update L [ ] [ ] as k has not been occurred so only index has to be incremented ; Perform the queries ; Type 1 query ; Type 2 query ; Driver code ; Queries ; Perform the queries | import numpy as np NEW_LINE MAX = 26 ; NEW_LINE def performQueries ( string , q , type_arr , ch , freq ) : NEW_LINE INDENT n = len ( string ) ; NEW_LINE L = np . zeros ( ( MAX , n ) ) ; NEW_LINE F = np . zeros ( ( MAX , n ) ) ; NEW_LINE cnt = [ 0 ] * MAX ; NEW_LINE for i in range ( n ) : NEW_LINE INDENT k = ord ( string [ i ] ) - ord ( ' a ' ) ; NEW_LINE cnt [ k ] += 1 ; NEW_LINE for j in range ( MAX ) : NEW_LINE INDENT if ( k == j ) : NEW_LINE INDENT L [ j ] [ cnt [ j ] ] = i ; NEW_LINE F [ j ] [ cnt [ j ] ] = i ; NEW_LINE DEDENT else : NEW_LINE INDENT L [ j ] [ cnt [ j ] ] = L [ j ] [ cnt [ j ] ] + 1 ; NEW_LINE DEDENT DEDENT DEDENT for i in range ( q ) : NEW_LINE INDENT if ( type_arr [ i ] == 1 ) : NEW_LINE INDENT print ( L [ ord ( ch [ i ] ) - ord ( ' a ' ) ] [ freq [ i ] ] , end = " " ) ; NEW_LINE DEDENT else : NEW_LINE INDENT print ( F [ ord ( ch [ i ] ) - ord ( ' a ' ) ] [ freq [ i ] ] , end = " " ) ; NEW_LINE DEDENT print ( ) NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT string = " geeksforgeeks " ; NEW_LINE type_arr = [ 1 , 2 ] ; NEW_LINE ch = [ ' e ' , ' k ' ] ; NEW_LINE freq = [ 2 , 2 ] ; NEW_LINE q = len ( type_arr ) ; NEW_LINE performQueries ( string , q , type_arr , ch , freq ) ; NEW_LINE DEDENT |
Number of index pairs such that s [ i ] and s [ j ] are anagrams | Function to find number of pairs of integers i , j such that s [ i ] is an anagram of s [ j ] . ; To store the count of sorted strings ; Traverse all strings and store in the map ; Sort the string ; If string exists in map , increment count Else create key value pair with count = 1 ; To store the number of pairs ; Traverse through the map ; Count the pairs for each string ; Return the required answer ; Driver code ; Function call | def anagram_pairs ( s , n ) : NEW_LINE INDENT mp = dict ( ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT temp_str = " " . join ( sorted ( s [ i ] ) ) NEW_LINE if temp_str in mp : NEW_LINE INDENT mp [ temp_str ] += 1 NEW_LINE DEDENT else : NEW_LINE INDENT mp [ temp_str ] = 1 NEW_LINE DEDENT DEDENT ans = 0 NEW_LINE for k in mp . values ( ) : NEW_LINE INDENT ans += ( k * ( k - 1 ) ) // 2 NEW_LINE DEDENT return ans NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT s = [ " aaab " , " aaba " , " baaa " , " cde " , " dec " ] NEW_LINE n = len ( s ) NEW_LINE print ( anagram_pairs ( s , n ) ) NEW_LINE DEDENT |
Insert a Character in a Rotated String | Function to insert the character ; To store last position where the insertion is done ; To store size of the string ; To store the modified string ; To store characters ; Add first character to the string ; Update the size ; Update the index of last insertion ; Insert all other characters to the string ; Take the character ; Take substring upto ind ; Take modulo value of k with the size of the string ; Check if we need to move to the start of the string ; If we don 't need to move to start of the string ; Take substring from upto temp ; Take substring which will be after the inserted character ; Insert into the string ; Store new inserted position ; Store size of the new string Technically sz + 1 ; If we need to move to start of the string ; Take substring which will before the inserted character ; Take substring which will be after the inserted character ; Insert into the string ; Store new inserted position ; Store size of the new string Technically sz + 1 ; Return the required character ; Driver Code ; Function call | def insert ( arr : list , n : int , k : int ) -> chr : NEW_LINE INDENT ind = 0 NEW_LINE sz = 0 NEW_LINE s = " " NEW_LINE ch = arr [ 0 ] NEW_LINE s += ch NEW_LINE sz = 1 NEW_LINE ind = 0 NEW_LINE for i in range ( 1 , n ) : NEW_LINE INDENT ch = arr [ i ] NEW_LINE s1 = s [ 0 : ind + 1 ] NEW_LINE temp = k % sz NEW_LINE ro = temp - min ( temp , sz - ind - 1 ) NEW_LINE if ro == 0 : NEW_LINE INDENT s2 = s [ ind + 1 : ind + 1 + temp ] NEW_LINE s3 = s [ ind + temp + 1 : sz ] NEW_LINE s = s1 + s2 + ch + s3 NEW_LINE ind = len ( s1 ) + len ( s2 ) NEW_LINE sz = len ( s ) NEW_LINE DEDENT else : NEW_LINE INDENT s2 = s [ : ro ] NEW_LINE s3 = s [ ro : sz ] NEW_LINE s = s2 + ch + s3 NEW_LINE ind = len ( s2 ) NEW_LINE sz = len ( s ) NEW_LINE DEDENT DEDENT if ind == 0 : NEW_LINE INDENT return s [ sz - 1 ] NEW_LINE DEDENT else : NEW_LINE INDENT return s [ ind - 1 ] NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ '1' , '2' , '3' , '4' , '5' ] NEW_LINE k = 2 NEW_LINE n = len ( arr ) NEW_LINE print ( insert ( arr , n , k ) ) NEW_LINE DEDENT |
Rearrange the given string such that all prime multiple indexes have same character | Python3 program to rearrange the given string such that all prime multiple indexes have same character ; To store answer ; Function to rearrange the given string such that all prime multiple indexes have the same character . ; Initially assume that we can kept any symbol at any positions . If at any index contains one then it is not counted in our required positions ; To store number of positions required to store elements of same kind ; Start sieve ; For all multiples of i ; map to store frequency of each character ; Store all characters in the vector and sort the vector to find the character with highest frequency ; If most occured character is less than required positions ; In all required positions keep character which occured most times ; Fill all other indexes with remaining characters ; If character frequency becomes zero then go to next character ; Driver code ; Function call | N = 100005 NEW_LINE ans = [ 0 ] * N ; NEW_LINE def Rearrange ( s , n ) : NEW_LINE INDENT sieve = [ 1 ] * ( N + 1 ) ; NEW_LINE sz = 0 ; NEW_LINE for i in range ( 2 , n // 2 + 1 ) : NEW_LINE INDENT if ( sieve [ i ] ) : NEW_LINE INDENT for j in range ( 1 , n // i + 1 ) : NEW_LINE INDENT if ( sieve [ i * j ] ) : NEW_LINE INDENT sz += 1 ; NEW_LINE DEDENT sieve [ i * j ] = 0 ; NEW_LINE DEDENT DEDENT DEDENT m = dict . fromkeys ( s , 0 ) ; NEW_LINE for it in s : NEW_LINE INDENT m [ it ] += 1 ; NEW_LINE DEDENT v = [ ] ; NEW_LINE for key , value in m . items ( ) : NEW_LINE INDENT v . append ( [ value , key ] ) ; NEW_LINE DEDENT v . sort ( ) ; NEW_LINE if ( v [ - 1 ] [ 0 ] < sz ) : NEW_LINE INDENT print ( - 1 , end = " " ) ; NEW_LINE return ; NEW_LINE DEDENT for i in range ( 2 , n + 1 ) : NEW_LINE INDENT if ( not sieve [ i ] ) : NEW_LINE INDENT ans [ i ] = v [ - 1 ] [ 1 ] ; NEW_LINE DEDENT DEDENT idx = 0 ; NEW_LINE for i in range ( 1 , n + 1 ) : NEW_LINE INDENT if ( sieve [ i ] ) : NEW_LINE INDENT ans [ i ] = v [ idx ] [ 1 ] ; NEW_LINE v [ idx ] [ 0 ] -= 1 ; NEW_LINE if ( v [ idx ] [ 0 ] == 0 ) : NEW_LINE INDENT idx += 1 ; NEW_LINE DEDENT DEDENT print ( ans [ i ] , end = " " ) ; NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT string = " aabaaaa " ; NEW_LINE n = len ( string ) ; NEW_LINE Rearrange ( string , n ) ; NEW_LINE DEDENT |
Check loop in array according to given constraints | A simple Graph DFS based recursive function to check if there is cycle in graph with vertex v as root of DFS . Refer below article for details . https : www . geeksforgeeks . org / detect - cycle - in - a - graph / ; There is a cycle if an adjacent is visited and present in recursion call stack recur [ ] ; Returns true if arr [ ] has cycle ; Create a graph using given moves in arr [ ] ; Do DFS traversal of graph to detect cycle ; Driver code | def isCycleRec ( v , adj , visited , recur ) : NEW_LINE INDENT visited [ v ] = True NEW_LINE recur [ v ] = True NEW_LINE for i in range ( len ( adj [ v ] ) ) : NEW_LINE INDENT if ( visited [ adj [ v ] [ i ] ] == False ) : NEW_LINE INDENT if ( isCycleRec ( adj [ v ] [ i ] , adj , visited , recur ) ) : NEW_LINE INDENT return True NEW_LINE DEDENT DEDENT elif ( visited [ adj [ v ] [ i ] ] == True and recur [ adj [ v ] [ i ] ] == True ) : NEW_LINE INDENT return True NEW_LINE DEDENT DEDENT recur [ v ] = False NEW_LINE return False NEW_LINE DEDENT def isCycle ( arr , n ) : NEW_LINE INDENT adj = [ [ ] for i in range ( n ) ] NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( i != ( i + arr [ i ] + n ) % n ) : NEW_LINE INDENT adj [ i ] . append ( ( i + arr [ i ] + n ) % n ) NEW_LINE DEDENT DEDENT visited = [ False ] * n NEW_LINE recur = [ False ] * n NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( visited [ i ] == False ) : NEW_LINE INDENT if ( isCycleRec ( i , adj , visited , recur ) ) : NEW_LINE INDENT return True NEW_LINE DEDENT DEDENT DEDENT return True NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 2 , - 1 , 1 , 2 , 2 ] NEW_LINE n = len ( arr ) NEW_LINE if ( isCycle ( arr , n ) ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT DEDENT |
Queries to find the last non | Maximum distinct characters possible ; To store the frequency of the characters ; Function to pre - calculate the frequency array ; Only the first character has frequency 1 till index 0 ; Starting from the second character of the string ; For every possible character ; Current character under consideration ; If it is equal to the character at the current index ; Function to return the frequency of the given character in the sub - string str [ l ... r ] ; Function to return the last non - repeating character ; Starting from the last character ; Current character ; If frequency of the current character is 1 then return the character ; All the characters of the sub - string are repeating ; Driver Code ; Pre - calculate the frequency array | MAX = 256 NEW_LINE freq = [ [ 0 for i in range ( 256 ) ] for j in range ( 1000 ) ] NEW_LINE def preCalculate ( string , n ) : NEW_LINE INDENT freq [ ord ( string [ 0 ] ) ] [ 0 ] = 1 NEW_LINE for i in range ( 1 , n ) : NEW_LINE INDENT ch = string [ i ] NEW_LINE for j in range ( MAX ) : NEW_LINE INDENT charToUpdate = chr ( j ) NEW_LINE if charToUpdate == ch : NEW_LINE INDENT freq [ j ] [ i ] = freq [ j ] [ i - 1 ] + 1 NEW_LINE DEDENT else : NEW_LINE INDENT freq [ j ] [ i ] = freq [ j ] [ i - 1 ] NEW_LINE DEDENT DEDENT DEDENT DEDENT def getFrequency ( ch , l , r ) : NEW_LINE INDENT if l == 0 : NEW_LINE INDENT return freq [ ord ( ch ) ] [ r ] NEW_LINE DEDENT else : NEW_LINE INDENT return ( freq [ ord ( ch ) ] [ r ] - freq [ ord ( ch ) ] [ l - 1 ] ) NEW_LINE DEDENT DEDENT def lastNonRepeating ( string , n , l , r ) : NEW_LINE INDENT for i in range ( r , l - 1 , - 1 ) : NEW_LINE INDENT ch = string [ i ] NEW_LINE if getFrequency ( ch , l , r ) == 1 : NEW_LINE INDENT return ch NEW_LINE DEDENT DEDENT return " - 1" NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT string = " GeeksForGeeks " NEW_LINE n = len ( string ) NEW_LINE queries = [ ( 2 , 9 ) , ( 2 , 3 ) , ( 0 , 12 ) ] NEW_LINE q = len ( queries ) NEW_LINE preCalculate ( string , n ) NEW_LINE for i in range ( q ) : NEW_LINE INDENT print ( lastNonRepeating ( string , n , queries [ i ] [ 0 ] , queries [ i ] [ 1 ] ) ) NEW_LINE DEDENT DEDENT |
Queries to answer the X | Function to pre - process the sub - strings in sorted order ; Generate all substrings ; Iterate to find all sub - strings ; Store the sub - string in the vector ; Sort the substrings lexicographically ; Driver code ; To store all the sub - strings ; Perform queries | def pre_process ( substrings , s ) : NEW_LINE INDENT n = len ( s ) ; NEW_LINE for i in range ( n ) : NEW_LINE INDENT dup = " " ; NEW_LINE for j in range ( i , n ) : NEW_LINE INDENT dup += s [ j ] ; NEW_LINE substrings . append ( dup ) ; NEW_LINE DEDENT DEDENT substrings . sort ( ) ; NEW_LINE return substrings ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT s = " geek " ; NEW_LINE substrings = [ ] ; NEW_LINE substrings = pre_process ( substrings , s ) ; NEW_LINE queries = [ 1 , 5 , 10 ] ; NEW_LINE q = len ( queries ) ; NEW_LINE for i in range ( q ) : NEW_LINE INDENT print ( substrings [ queries [ i ] - 1 ] ) ; NEW_LINE DEDENT DEDENT |
Smallest subsequence having GCD equal to GCD of given array | Python3 program to implement the above approach ; Function to print the smallest subsequence that satisfies the condition ; Stores gcd of the array . ; Traverse the given array ; Update gcdArr ; Traverse the given array . ; If current element equal to gcd of array . ; Generate all possible pairs . ; If gcd of current pair equal to gcdArr ; Print current pair of the array ; Driver Code | import math NEW_LINE def printSmallSub ( arr , N ) : NEW_LINE INDENT gcdArr = 0 NEW_LINE for i in range ( 0 , N ) : NEW_LINE INDENT gcdArr = math . gcd ( gcdArr , arr [ i ] ) NEW_LINE DEDENT for i in range ( 0 , N ) : NEW_LINE INDENT if ( arr [ i ] == gcdArr ) : NEW_LINE INDENT print ( arr [ i ] , end = " β " ) NEW_LINE return NEW_LINE DEDENT for i in range ( 0 , N ) : NEW_LINE INDENT for j in range ( i + 1 , N ) : NEW_LINE INDENT if ( math . gcd ( arr [ i ] , arr [ j ] ) == gcdArr ) : NEW_LINE INDENT print ( arr [ i ] , end = " β " ) NEW_LINE print ( arr [ j ] , end = " β " ) NEW_LINE return NEW_LINE DEDENT DEDENT DEDENT DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 4 , 6 , 12 ] NEW_LINE N = len ( arr ) NEW_LINE printSmallSub ( arr , N ) NEW_LINE DEDENT |
Minimum cost to modify a string | Function to return the minimum cost ; Initialize result ; To store the frequency of characters of the string ; Update the frequencies of the characters of the string ; Loop to check all windows from a - z where window size is K ; Starting index of window ; Ending index of window ; Check if the string contains character ; Check if the character is on left side of window find the cost of modification for character add value to count calculate nearest distance of modification ; Check if the character is on right side of window find the cost of modification for character add value to count calculate nearest distance of modification ; Find the minimum of all costs for modifying the string ; Loop to check all windows Here window contains characters before z and after z of window size K ; Starting index of window ; Ending index of window ; Check if the string contains character ; If characters are outside window find the cost for modifying character add value to count ; Find the minimum of all costs for modifying the string ; Driver code | def minCost ( str1 , K ) : NEW_LINE INDENT n = len ( str1 ) NEW_LINE res = 999999999 NEW_LINE count = 0 NEW_LINE cnt = [ 0 for i in range ( 27 ) ] NEW_LINE for i in range ( n ) : NEW_LINE INDENT cnt [ ord ( str1 [ i ] ) - ord ( ' a ' ) + 1 ] += 1 NEW_LINE DEDENT for i in range ( 1 , 26 - K + 1 , 1 ) : NEW_LINE INDENT a = i NEW_LINE b = i + K NEW_LINE count = 0 NEW_LINE for j in range ( 1 , 27 , 1 ) : NEW_LINE INDENT if ( cnt [ j ] > 0 ) : NEW_LINE INDENT if ( j >= a and j >= b ) : NEW_LINE INDENT count = count + ( min ( j - b , 25 - j + a + 1 ) ) * cnt [ j ] NEW_LINE DEDENT elif ( j <= a and j <= b ) : NEW_LINE INDENT count = count + ( min ( a - j , 25 + j - b + 1 ) ) * cnt [ j ] NEW_LINE DEDENT DEDENT DEDENT res = min ( res , count ) NEW_LINE DEDENT for i in range ( 26 - K + 1 , 27 , 1 ) : NEW_LINE INDENT a = i NEW_LINE b = ( i + K ) % 26 NEW_LINE count = 0 NEW_LINE for j in range ( 1 , 27 , 1 ) : NEW_LINE INDENT if ( cnt [ j ] > 0 ) : NEW_LINE INDENT if ( j >= b and j <= a ) : NEW_LINE INDENT count = count + ( min ( j - b , a - j ) ) * cnt [ j ] NEW_LINE DEDENT DEDENT DEDENT res = min ( res , count ) NEW_LINE DEDENT return res NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT str1 = " abcdefghi " NEW_LINE K = 2 NEW_LINE print ( minCost ( str1 , K ) ) NEW_LINE DEDENT |
Generate all binary strings of length n with sub | Utility function to print the given binary string ; This function will be called recursively to generate the next bit for given binary string according to its current state ; Base - case : if the generated binary string meets the required length and the pattern "01" appears twice ; nextbit needs to be 0 because each time we call the function recursively , we call 2 times for 2 cases : next bit is 0 or 1 The is to assure that the binary string is printed one time only ; Generate the next bit for str and call recursive ; Assign first bit ; The next generated bit will either be 0 or 1 ; If pattern "01" occurrence is < 2 ; Set next bit ; If pattern "01" appears then increase the occurrence of pattern ; Else pattern "01" occurrence equals 2 ; If previous bit is 0 then next bit cannot be 1 ; Otherwise ; Driver code ; Length of the resulting strings must be at least 4 ; Generate all binary strings of length n with sub - string "01" appearing twice | def printBinStr ( string , length ) : NEW_LINE INDENT for i in range ( 0 , length ) : NEW_LINE INDENT print ( string [ i ] , end = " " ) NEW_LINE DEDENT print ( ) NEW_LINE DEDENT def generateBinStr ( string , length , currlen , occur , nextbit ) : NEW_LINE INDENT if currlen == length : NEW_LINE INDENT if occur == 2 and nextbit == 0 : NEW_LINE INDENT printBinStr ( string , length ) NEW_LINE DEDENT return NEW_LINE DEDENT if currlen == 0 : NEW_LINE INDENT string [ 0 ] = nextbit NEW_LINE generateBinStr ( string , length , currlen + 1 , occur , 0 ) NEW_LINE generateBinStr ( string , length , currlen + 1 , occur , 1 ) NEW_LINE DEDENT else : NEW_LINE INDENT if occur < 2 : NEW_LINE INDENT string [ currlen ] = nextbit NEW_LINE if string [ currlen - 1 ] == 0 and nextbit == 1 : NEW_LINE INDENT occur += 1 NEW_LINE DEDENT generateBinStr ( string , length , currlen + 1 , occur , 0 ) NEW_LINE generateBinStr ( string , length , currlen + 1 , occur , 1 ) NEW_LINE DEDENT else : NEW_LINE INDENT if string [ currlen - 1 ] == 0 and nextbit == 1 : NEW_LINE INDENT return NEW_LINE DEDENT else : NEW_LINE INDENT string [ currlen ] = nextbit NEW_LINE generateBinStr ( string , length , currlen + 1 , occur , 0 ) NEW_LINE generateBinStr ( string , length , currlen + 1 , occur , 1 ) NEW_LINE DEDENT DEDENT DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT n = 5 NEW_LINE if n < 4 : NEW_LINE INDENT print ( - 1 ) NEW_LINE DEDENT else : NEW_LINE INDENT string = [ None ] * n NEW_LINE generateBinStr ( string , n , 0 , 0 , 0 ) NEW_LINE generateBinStr ( string , n , 0 , 0 , 1 ) NEW_LINE DEDENT DEDENT |
Print last character of each word in a string | Function to print the last character of each word in the given string ; Now , last word is also followed by a space ; If current character is a space ; Then previous character must be the last character of some word ; Driver code | def printLastChar ( string ) : NEW_LINE INDENT string = string + " β " NEW_LINE for i in range ( len ( string ) ) : NEW_LINE INDENT if string [ i ] == ' β ' : NEW_LINE INDENT print ( string [ i - 1 ] , end = " β " ) NEW_LINE DEDENT DEDENT DEDENT string = " Geeks β for β Geeks " NEW_LINE printLastChar ( string ) NEW_LINE |
Maximum length of balanced string after swapping and removal of characters | Function to return the length of the longest balanced sub - string ; To store the count of parentheses ; Traversing the string ; Check type of parentheses and incrementing count for it ; Sum all pair of balanced parentheses ; Driven code | def maxBalancedStr ( s ) : NEW_LINE INDENT open1 = 0 NEW_LINE close1 = 0 NEW_LINE open2 = 0 NEW_LINE close2 = 0 NEW_LINE open3 = 0 NEW_LINE close3 = 0 NEW_LINE for i in range ( len ( s ) ) : NEW_LINE INDENT if ( s [ i ] == ' ( ' ) : open1 += 1 continue if s [ i ] == ' ) ' : NEW_LINE INDENT close1 += 1 NEW_LINE continue NEW_LINE DEDENT if s [ i ] == ' { ' : NEW_LINE INDENT open2 += 1 NEW_LINE continue NEW_LINE DEDENT if s [ i ] == ' } ' : NEW_LINE INDENT close2 += 1 NEW_LINE continue NEW_LINE DEDENT if s [ i ] == ' [ ' : NEW_LINE INDENT open3 += 1 NEW_LINE continue NEW_LINE DEDENT if s [ i ] == ' ] ' : NEW_LINE INDENT close3 += 1 NEW_LINE continue NEW_LINE DEDENT DEDENT maxLen = ( 2 * min ( open1 , close1 ) + 2 * min ( open2 , close2 ) + 2 * min ( open3 , close3 ) ) NEW_LINE return maxLen NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : s = " ) ) [ ] ] ( ( " NEW_LINE INDENT print ( maxBalancedStr ( s ) ) NEW_LINE DEDENT |
Bitwise OR of N binary strings | Function to return the bitwise OR of all the binary strings ; Get max size and reverse each string Since we have to perform OR operation on bits from right to left Reversing the string will make it easier to perform operation from left to right ; Add 0 s to the end of strings if needed ; Perform OR operation on each bit ; Reverse the resultant string to get the final string ; Return the final string ; Driver code | def strBitwiseOR ( arr , n ) : NEW_LINE INDENT res = " " NEW_LINE max_size = - ( 2 ** 32 ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT max_size = max ( max_size , len ( arr [ i ] ) ) NEW_LINE arr [ i ] = arr [ i ] [ : : - 1 ] NEW_LINE DEDENT for i in range ( n ) : NEW_LINE INDENT s = " " NEW_LINE for j in range ( max_size - len ( arr [ i ] ) ) : NEW_LINE INDENT s += '0' NEW_LINE DEDENT arr [ i ] = arr [ i ] + s NEW_LINE DEDENT for i in range ( max_size ) : NEW_LINE INDENT curr_bit = 0 NEW_LINE for j in range ( n ) : NEW_LINE INDENT curr_bit = curr_bit | ord ( arr [ j ] [ i ] ) NEW_LINE DEDENT res += chr ( curr_bit ) NEW_LINE DEDENT res = res [ : : - 1 ] NEW_LINE return res NEW_LINE DEDENT arr = [ "10" , "11" , "1000001" ] NEW_LINE n = len ( arr ) NEW_LINE print ( strBitwiseOR ( arr , n ) ) NEW_LINE |
Minimum cost to make two strings same | Function to return the minimum cost to make the configuration of both the strings same ; Iterate and find the cost ; Find the minimum cost ; Driver Code | def findCost ( s1 , s2 , a , b , c , d , n ) : NEW_LINE INDENT cost = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( s1 [ i ] == s2 [ i ] ) : NEW_LINE INDENT continue NEW_LINE DEDENT else : NEW_LINE INDENT if ( ( s1 [ i ] == '1' and s2 [ i ] == '2' ) or ( s2 [ i ] == '1' and s1 [ i ] == '2' ) ) : NEW_LINE INDENT cost += min ( d , min ( a , b + c ) ) NEW_LINE DEDENT elif ( ( s1 [ i ] == '2' and s2 [ i ] == '3' ) or ( s2 [ i ] == '2' and s1 [ i ] == '3' ) ) : NEW_LINE INDENT cost += min ( d , min ( b , a + c ) ) NEW_LINE DEDENT elif ( ( s1 [ i ] == '1' and s2 [ i ] == '3' ) or ( s2 [ i ] == '1' and s1 [ i ] == '3' ) ) : NEW_LINE INDENT cost += min ( d , min ( c , a + b ) ) NEW_LINE DEDENT DEDENT DEDENT return cost NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT s1 = "121" NEW_LINE s2 = "223" NEW_LINE a = 2 NEW_LINE b = 3 NEW_LINE c = 4 NEW_LINE d = 10 NEW_LINE n = len ( s1 ) NEW_LINE print ( findCost ( s1 , s2 , a , b , c , d , n ) ) NEW_LINE DEDENT |
Count the number of common divisors of the given strings | Function that returns true if sub - string s [ 0. . . k ] is repeated a number of times to generate String s ; Function to return the count of common divisors ; If the length of the sub - string divides length of both the strings ; If prefixes match in both the strings ; If both the strings can be generated ; Driver code | def check ( s , k ) : NEW_LINE INDENT for i in range ( 0 , len ( s ) ) : NEW_LINE INDENT if ( s [ i ] != s [ i % k ] ) : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT return True NEW_LINE DEDENT def countCommonDivisors ( a , b ) : NEW_LINE INDENT ct = 0 NEW_LINE n = len ( a ) NEW_LINE m = len ( b ) NEW_LINE for i in range ( 1 , min ( n , m ) + 1 ) : NEW_LINE INDENT if ( n % i == 0 and m % i == 0 ) : NEW_LINE INDENT if ( a [ 0 : i ] == b [ 0 : i ] ) : NEW_LINE INDENT if ( check ( a , i ) and check ( b , i ) ) : NEW_LINE INDENT ct = ct + 1 NEW_LINE DEDENT DEDENT DEDENT DEDENT return ct NEW_LINE DEDENT a = " xaxa " NEW_LINE b = " xaxaxaxa " NEW_LINE print ( countCommonDivisors ( a , b ) ) NEW_LINE |
Level order traversal line by line | Set 3 ( Using One Queue ) | Python3 program to print levels line by line ; A Binary Tree Node ; Function to do level order traversal line by line ; Create an empty queue for level order traversal ; Pushing root node into the queue . ; Pushing delimiter into the queue . ; Condition to check occurrence of next level . ; Pushing left child of current node . ; Pushing left child current node ; Pushing right child of current node . ; Driver code ; Let us create binary tree shown above | from collections import deque as queue NEW_LINE class Node : NEW_LINE INDENT def __init__ ( self , key ) : NEW_LINE INDENT self . data = key NEW_LINE self . left = None NEW_LINE self . right = None NEW_LINE DEDENT DEDENT def levelOrder ( root ) : NEW_LINE INDENT if ( root == None ) : NEW_LINE INDENT return NEW_LINE DEDENT q = queue ( ) NEW_LINE q . append ( root ) NEW_LINE q . append ( None ) NEW_LINE while ( len ( q ) > 1 ) : NEW_LINE INDENT curr = q . popleft ( ) NEW_LINE if ( curr == None ) : NEW_LINE q . append ( None ) NEW_LINE print ( ) NEW_LINE else : NEW_LINE INDENT if ( curr . left ) : NEW_LINE INDENT q . append ( curr . left ) NEW_LINE DEDENT if ( curr . right ) : NEW_LINE INDENT q . append ( curr . right ) NEW_LINE DEDENT print ( curr . data , end = " β " ) NEW_LINE DEDENT DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT root = Node ( 1 ) NEW_LINE root . left = Node ( 2 ) NEW_LINE root . right = Node ( 3 ) NEW_LINE root . left . left = Node ( 4 ) NEW_LINE root . left . right = Node ( 5 ) NEW_LINE root . right . right = Node ( 6 ) NEW_LINE levelOrder ( root ) NEW_LINE DEDENT |
Convert given string so that it holds only distinct characters | Function to return the index of the character that has 0 occurrence starting from index i ; If current character has 0 occurrence ; If no character has 0 occurrence ; Function to return the modified string which consists of distinct characters ; String cannot consist of all distinct characters ; Count the occurrences for each of the character ; Index for the first character that hasn 't appeared in the string ; If current character appeared more than once then it has to be replaced with some character that hasn 't occurred yet ; Decrement current character 's occurrence by 1 ; Replace the character ; Update the new character ' s β occurrence β β This β step β can β also β be β skipped β as β β we ' ll never encounter this character in the string because it has been added just now ; Find the next character that hasn 't occurred yet ; Driver code | def nextZero ( i , occurrences ) : NEW_LINE INDENT while i < 26 : NEW_LINE INDENT if occurrences [ i ] == 0 : NEW_LINE INDENT return i NEW_LINE DEDENT i += 1 NEW_LINE DEDENT return - 1 NEW_LINE DEDENT def getModifiedString ( str ) : NEW_LINE INDENT n = len ( str ) NEW_LINE if n > 26 : NEW_LINE INDENT return " - 1" NEW_LINE DEDENT ch = str NEW_LINE ch = list ( ch ) NEW_LINE occurrences = [ 0 ] * 26 NEW_LINE for i in range ( n ) : NEW_LINE INDENT occurrences [ ord ( ch [ i ] ) - ord ( ' a ' ) ] += 1 NEW_LINE DEDENT index = nextZero ( 0 , occurrences ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT if occurrences [ ord ( ch [ i ] ) - ord ( ' a ' ) ] > 1 : NEW_LINE INDENT occurrences [ ord ( ch [ i ] ) - ord ( ' a ' ) ] -= 1 NEW_LINE ch [ i ] = chr ( ord ( ' a ' ) + index ) NEW_LINE occurrences [ index ] = 1 NEW_LINE index = nextZero ( index + 1 , occurrences ) NEW_LINE DEDENT DEDENT ch = ' ' . join ( ch ) NEW_LINE print ( ch ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT str = " geeksforgeeks " NEW_LINE getModifiedString ( str ) NEW_LINE DEDENT |
Replace all occurrences of a string with space | Function to extract the secret message ; Replacing all occurrences of Sub in Str by empty spaces ; Removing unwanted spaces in the start and end of the string ; Driver code | def extractSecretMessage ( Str , Sub ) : NEW_LINE INDENT Str = Str . replace ( Sub , " β " ) NEW_LINE return Str . strip ( ) NEW_LINE DEDENT Str = " LIELIEILIEAMLIECOOL " NEW_LINE Sub = " LIE " NEW_LINE print ( extractSecretMessage ( Str , Sub ) ) NEW_LINE |
Sub | Function to return the count of sub - strings starting from startIndex that are also the prefixes of string ; Function to return the count of all possible sub - strings of string that are also the prefixes of string ; If current character is equal to the starting character of str ; Driver Code ; Function Call | def subStringsStartingHere ( string , n , startIndex ) : NEW_LINE INDENT count = 0 NEW_LINE i = startIndex + 1 NEW_LINE while ( i <= n ) : NEW_LINE INDENT if string . startswith ( string [ startIndex : i ] ) : NEW_LINE INDENT count += 1 NEW_LINE DEDENT else : NEW_LINE INDENT break NEW_LINE DEDENT i += 1 NEW_LINE DEDENT return count NEW_LINE DEDENT def countSubStrings ( string , n ) : NEW_LINE INDENT count = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT if string [ i ] == string [ 0 ] : NEW_LINE INDENT count += subStringsStartingHere ( string , n , i ) NEW_LINE DEDENT DEDENT return count NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT string = " ababc " NEW_LINE n = len ( string ) NEW_LINE print ( countSubStrings ( string , n ) ) NEW_LINE DEDENT |
Binary Search a String | Returns index of x if it is present in arr [ ] , else return - 1 ; Check if x is present at mid ; If x greater , ignore left half ; If x is smaller , ignore right half ; Driver Code | def binarySearch ( arr , x ) : NEW_LINE INDENT l = 0 NEW_LINE r = len ( arr ) NEW_LINE while ( l <= r ) : NEW_LINE INDENT m = l + ( ( r - l ) // 2 ) NEW_LINE res = ( x == arr [ m ] ) NEW_LINE if ( res == 0 ) : NEW_LINE INDENT return m - 1 NEW_LINE DEDENT if ( res > 0 ) : NEW_LINE INDENT l = m + 1 NEW_LINE DEDENT else : NEW_LINE INDENT r = m - 1 NEW_LINE DEDENT DEDENT return - 1 NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ " contribute " , " geeks " , " ide " , " practice " ] ; NEW_LINE x = " ide " NEW_LINE result = binarySearch ( arr , x ) NEW_LINE if ( result == - 1 ) : NEW_LINE INDENT print ( " Element β not β present " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " Element β found β at β index " , result ) NEW_LINE DEDENT DEDENT |
Count characters in a string whose ASCII values are prime | Python3 implementation of above approach ; Function to find prime characters in the string ; 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 . ; 0 and 1 are not primes ; If prime [ p ] is not changed , then it is a prime ; Update all multiples of p ; Traverse all the characters ; Driver program ; print required answer | from math import sqrt NEW_LINE max_val = 257 NEW_LINE def PrimeCharacters ( s ) : NEW_LINE INDENT prime = [ True ] * ( 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 ) : NEW_LINE INDENT if ( prime [ p ] == True ) : NEW_LINE INDENT for i in range ( 2 * p , max_val + 1 , p ) : NEW_LINE INDENT prime [ i ] = False NEW_LINE DEDENT DEDENT DEDENT count = 0 NEW_LINE for i in range ( len ( s ) ) : NEW_LINE INDENT if ( prime [ ord ( s [ i ] ) ] ) : NEW_LINE INDENT count += 1 NEW_LINE DEDENT DEDENT return count NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT S = " geeksforgeeks " ; NEW_LINE print ( PrimeCharacters ( S ) ) NEW_LINE DEDENT |
Length of largest subsequence consisting of a pair of alternating digits | Function to find the length of the largest subsequence consisting of a pair of alternating digits ; Variable initialization ; Nested loops for iteration ; Check if i is not equal to j ; Initialize length as 0 ; Iterate from 0 till the size of the string ; Increment length ; Increment length ; Update maxi ; Check if maxi is not equal to 1 the print otherwise pr0 ; Driver Code ; Given string ; Function call | def largestSubsequence ( s ) : NEW_LINE INDENT maxi = 0 NEW_LINE for i in range ( 10 ) : NEW_LINE INDENT for j in range ( 10 ) : NEW_LINE INDENT if ( i != j ) : NEW_LINE INDENT lenn = 0 NEW_LINE prev1 = chr ( j + ord ( '0' ) ) NEW_LINE for k in range ( len ( s ) ) : NEW_LINE INDENT if ( s [ k ] == chr ( i + ord ( '0' ) ) and prev1 == chr ( j + ord ( '0' ) ) ) : NEW_LINE INDENT prev1 = s [ k ] NEW_LINE lenn += 1 NEW_LINE DEDENT elif ( s [ k ] == chr ( j + ord ( '0' ) ) and prev1 == chr ( i + ord ( '0' ) ) ) : NEW_LINE INDENT prev1 = s [ k ] NEW_LINE lenn += 1 NEW_LINE DEDENT DEDENT maxi = max ( lenn , maxi ) NEW_LINE DEDENT DEDENT DEDENT if ( maxi != 1 ) : NEW_LINE INDENT print ( maxi ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( 0 ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT s = "1542745249842" NEW_LINE largestSubsequence ( s ) NEW_LINE DEDENT |
Students with maximum average score of three subjects | Function to find the list of students having maximum average score ; Variables to store maximum average score ; List to store names of students having maximum average score ; Traversing the file data ; finding average score of a student ; Clear the list and add name of student having current maximum average score in the list ; Printing the maximum average score and names of students having this maximum average score as per the order in the file . ; Driver Code ; Number of elements in string array | def getStudentsList ( file ) : NEW_LINE INDENT maxAvgScore = 0 NEW_LINE names = [ ] NEW_LINE for i in range ( 0 , len ( file ) , 4 ) : NEW_LINE INDENT avgScore = ( int ( file [ i + 1 ] ) + int ( file [ i + 2 ] ) + int ( file [ i + 3 ] ) ) // 3 NEW_LINE if avgScore > maxAvgScore : NEW_LINE INDENT maxAvgScore = avgScore NEW_LINE names . clear ( ) NEW_LINE names . append ( file [ i ] ) NEW_LINE DEDENT elif avgScore == maxAvgScore : NEW_LINE INDENT names . add ( file [ i ] ) NEW_LINE DEDENT DEDENT for i in range ( len ( names ) ) : NEW_LINE INDENT print ( names [ i ] , end = " β " ) NEW_LINE DEDENT print ( maxAvgScore ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT file = [ " Shrikanth " , "20" , "30" , "10" , " Ram " , "100" , "50" , "10" ] NEW_LINE getStudentsList ( file ) NEW_LINE DEDENT |
Number of sub | Python3 program to find the number of sub - strings of s1 which are anagram of any sub - string of s2 ; This function returns true if contents of arr1 [ ] and arr2 [ ] are same , otherwise false . ; This function search for all permutations of string pat [ ] in string txt [ ] ; countP [ ] : Store count of all characters of pattern countTW [ ] : Store count of current window of text ; Traverse through remaining characters of pattern ; Compare counts of current window of text with counts of pattern [ ] ; cout << pat << " β " << txt << " β " ; ; Add current character to current window ; Remove the first character of previous window ; Check for the last window in text ; Function to return the number of sub - strings of s1 that are anagrams of any sub - string of s2 ; initializing variables ; outer loop for picking starting point ; loop for different length of substrings ; If s2 has any substring which is anagram of s1 . substr ( i , len ) ; increment the count ; Driver Code | ALL_CHARS = 256 NEW_LINE def compare ( arr1 , arr2 ) : NEW_LINE INDENT for i in range ( ALL_CHARS ) : NEW_LINE INDENT if arr1 [ i ] != arr2 [ i ] : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT return True NEW_LINE DEDENT def search ( pat , txt ) : NEW_LINE INDENT M = len ( pat ) NEW_LINE N = len ( txt ) NEW_LINE countP = [ 0 ] * ALL_CHARS NEW_LINE countTW = [ 0 ] * ALL_CHARS NEW_LINE for i in range ( M ) : NEW_LINE INDENT countP [ ord ( pat [ i ] ) ] += 1 NEW_LINE countTW [ ord ( txt [ i ] ) ] += 1 NEW_LINE DEDENT for i in range ( M , N ) : NEW_LINE INDENT if compare ( countP , countTW ) : NEW_LINE INDENT return True NEW_LINE DEDENT countTW [ ord ( txt [ i ] ) ] += 1 NEW_LINE countTW [ ord ( txt [ i - M ] ) ] -= 1 NEW_LINE DEDENT if compare ( countP , countTW ) : NEW_LINE INDENT return True NEW_LINE DEDENT return False NEW_LINE DEDENT def calculateSubString ( s1 , s2 , n ) : NEW_LINE INDENT count , j , x = 0 , 0 , 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT for length in range ( 1 , n - i + 1 ) : NEW_LINE INDENT if search ( s1 [ i : i + length ] , s2 ) : NEW_LINE INDENT count += 1 NEW_LINE DEDENT DEDENT DEDENT return count NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT str1 = " PLEASEHELPIMTRAPPED " NEW_LINE str2 = " INAKICKSTARTFACTORY " NEW_LINE length = len ( str1 ) NEW_LINE print ( calculateSubString ( str1 , str2 , length ) ) NEW_LINE DEDENT |
Sum of the alphabetical values of the characters of a string | Function to find string score ; Driver code | def strScore ( str , s , n ) : NEW_LINE INDENT score = 0 NEW_LINE index = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( str [ i ] == s ) : NEW_LINE INDENT for j in range ( len ( s ) ) : NEW_LINE INDENT score += ( ord ( s [ j ] ) - ord ( ' a ' ) + 1 ) NEW_LINE DEDENT index = i + 1 NEW_LINE break NEW_LINE DEDENT DEDENT score = score * index NEW_LINE return score NEW_LINE DEDENT str = [ " sahil " , " shashanak " , " sanjit " , " abhinav " , " mohit " ] NEW_LINE s = " abhinav " NEW_LINE n = len ( str ) NEW_LINE score = strScore ( str , s , n ) ; NEW_LINE print ( score ) NEW_LINE |
Minimum swaps to group similar characters side by side ? | checks whether a string has similar characters side by side ; If similar chars side by side , continue ; If we have found a char equal to current char and does not exist side to it , return false ; counts min swap operations to convert a string that has similar characters side by side ; Base case ; considering swapping of i and l chars ; Backtrack ; not considering swapping of i and l chars ; taking min of above two ; Driver Code | from sys import maxsize NEW_LINE def sameCharAdj ( string ) : NEW_LINE INDENT n = len ( string ) NEW_LINE st = set ( ) NEW_LINE st . add ( string [ 0 ] ) NEW_LINE for i in range ( 1 , n ) : NEW_LINE INDENT if string [ i ] == string [ i - 1 ] : NEW_LINE INDENT continue NEW_LINE DEDENT if string [ i ] in st : NEW_LINE INDENT return False NEW_LINE DEDENT st . add ( string [ i ] ) NEW_LINE DEDENT return True NEW_LINE DEDENT def minSwaps ( string , l , r , cnt , minm ) : NEW_LINE INDENT if l == r : NEW_LINE INDENT if sameCharAdj ( string ) : NEW_LINE INDENT return cnt NEW_LINE DEDENT else : NEW_LINE INDENT return maxsize NEW_LINE DEDENT DEDENT for i in range ( l + 1 , r + 1 , 1 ) : NEW_LINE INDENT string [ i ] , string [ l ] = string [ l ] , string [ i ] NEW_LINE cnt += 1 NEW_LINE x = minSwaps ( string , l + 1 , r , cnt , minm ) NEW_LINE string [ i ] , string [ l ] = string [ l ] , string [ i ] NEW_LINE cnt -= 1 NEW_LINE y = minSwaps ( string , l + 1 , r , cnt , minm ) NEW_LINE minm = min ( minm , min ( x , y ) ) NEW_LINE DEDENT return minm NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT string = " abbaacb " NEW_LINE string = list ( string ) NEW_LINE n = len ( string ) NEW_LINE cnt = 0 NEW_LINE minm = maxsize NEW_LINE print ( minSwaps ( string , 0 , n - 1 , cnt , minm ) ) NEW_LINE DEDENT |
Union | Naive implementation of find ; Naive implementation of union ( ) | def find ( parent , i ) : NEW_LINE INDENT if ( parent [ i ] == - 1 ) : NEW_LINE INDENT return i NEW_LINE DEDENT return find ( parent , parent [ i ] ) NEW_LINE DEDENT def Union ( parent , x , y ) : NEW_LINE INDENT xset = find ( parent , x ) NEW_LINE yset = find ( parent , y ) NEW_LINE parent [ xset ] = yset NEW_LINE DEDENT |
Get K | Function to return the K - th letter from new String . ; finding size = length of new string S ; get the K - th letter ; Driver Code | def K_thletter ( S , K ) : NEW_LINE INDENT N = len ( S ) NEW_LINE size = 0 NEW_LINE DEDENT ' NEW_LINE INDENT for i in range ( 0 , N ) : NEW_LINE INDENT if S [ i ] . isdigit ( ) : NEW_LINE INDENT size = size * int ( S [ i ] ) NEW_LINE DEDENT else : NEW_LINE INDENT size += 1 NEW_LINE DEDENT DEDENT for i in range ( N - 1 , - 1 , - 1 ) : NEW_LINE INDENT K %= size NEW_LINE if K == 0 and S [ i ] . isalpha ( ) : NEW_LINE INDENT return S [ i ] NEW_LINE DEDENT if S [ i ] . isdigit ( ) : NEW_LINE INDENT size = size // int ( S [ i ] ) NEW_LINE DEDENT else : NEW_LINE INDENT size -= 1 NEW_LINE DEDENT DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT S = " geeks2for2" NEW_LINE K = 15 NEW_LINE print ( K_thletter ( S , K ) ) NEW_LINE DEDENT |
Minimum number of Parentheses to be added to make it valid | Function to return required minimum number ; maintain balance of string ; It is guaranteed bal >= - 1 ; Driver code ; Function to print required answer | def minParentheses ( p ) : NEW_LINE INDENT bal = 0 NEW_LINE ans = 0 NEW_LINE for i in range ( 0 , len ( p ) ) : NEW_LINE INDENT if ( p [ i ] == ' ( ' ) : NEW_LINE INDENT bal += 1 NEW_LINE DEDENT else : NEW_LINE INDENT bal += - 1 NEW_LINE DEDENT if ( bal == - 1 ) : NEW_LINE INDENT ans += 1 NEW_LINE bal += 1 NEW_LINE DEDENT DEDENT return bal + ans NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT p = " ( ) ) " NEW_LINE print ( minParentheses ( p ) ) NEW_LINE DEDENT |
Check if suffix and prefix of a string are palindromes | Function to check whether the string is a palindrome ; Reverse the string and assign it to new variable for comparison ; check if both are same ; Function to check whether the string has prefix and suffix substrings of length greater than 1 which are palindromes . ; check all prefix substrings ; check if the prefix substring is a palindrome ; If we did not find any palindrome prefix of length greater than 1. ; check all suffix substrings , as the string is reversed now ; check if the suffix substring is a palindrome ; If we did not find a suffix ; Driver code | def isPalindrome ( r ) : NEW_LINE INDENT p = r [ : : - 1 ] NEW_LINE return r == p NEW_LINE DEDENT def CheckStr ( s ) : NEW_LINE INDENT l = len ( s ) NEW_LINE i = 0 NEW_LINE for i in range ( 2 , l + 1 ) : NEW_LINE INDENT if isPalindrome ( s [ 0 : i ] ) == True : NEW_LINE INDENT break NEW_LINE DEDENT DEDENT if i == ( l + 1 ) : NEW_LINE INDENT return False NEW_LINE DEDENT for i in range ( 2 , l + 1 ) : NEW_LINE INDENT if isPalindrome ( s [ l - i : l ] ) == True : NEW_LINE INDENT return True NEW_LINE DEDENT DEDENT return False NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT s = " abccbarfgdbd " NEW_LINE if CheckStr ( s ) == True : NEW_LINE INDENT print ( " YES " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " NO " ) NEW_LINE DEDENT DEDENT |
Count of ways to generate a Matrix with product of each row and column as 1 or | Function to return the number of possible ways ; Check if product can be - 1 ; driver code | def Solve ( N , M ) : NEW_LINE INDENT temp = ( N - 1 ) * ( M - 1 ) NEW_LINE ans = pow ( 2 , temp ) NEW_LINE if ( ( N + M ) % 2 != 0 ) : NEW_LINE INDENT print ( ans ) NEW_LINE else : NEW_LINE print ( 2 * ans ) NEW_LINE if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N , M = 3 , 3 NEW_LINE Solve ( N , M ) NEW_LINE DEDENT DEDENT DEDENT |
Rotations of a Binary String with Odd Value | function to calculate total odd equivalent ; Driver code | def oddEquivalent ( s , n ) : NEW_LINE INDENT count = 0 NEW_LINE for i in range ( 0 , n ) : NEW_LINE INDENT if ( s [ i ] == '1' ) : NEW_LINE INDENT count = count + 1 NEW_LINE DEDENT DEDENT return count NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT s = "1011011" NEW_LINE n = len ( s ) NEW_LINE print ( oddEquivalent ( s , n ) ) NEW_LINE DEDENT |
Minimum operation require to make first and last character same | Python3 program to find minimum operation require to make first and last character same ; Return the minimum operation require to make string first and last character same . ; Store indexes of first occurrences of characters . ; Initialize result ; Traverse through all characters ; Find first occurrence ; Update result for subsequent occurrences ; Driver Code | MAX = 256 NEW_LINE def minimumOperation ( s ) : NEW_LINE INDENT n = len ( s ) NEW_LINE first_occ = [ - 1 ] * MAX NEW_LINE res = float ( ' inf ' ) NEW_LINE for i in range ( 0 , n ) : NEW_LINE INDENT x = s [ i ] NEW_LINE if first_occ [ ord ( x ) ] == - 1 : NEW_LINE INDENT first_occ [ ord ( x ) ] = i NEW_LINE DEDENT else : NEW_LINE INDENT last_occ = n - i - 1 NEW_LINE res = min ( res , first_occ [ ord ( x ) ] + last_occ ) NEW_LINE DEDENT DEDENT return res NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT s = " bacdefghipalop " NEW_LINE print ( minimumOperation ( s ) ) NEW_LINE DEDENT |
Lexicographically smallest and largest substring of size k | Python 3 program to find lexicographically largest and smallest substrings of size k . ; Initialize min and max as first substring of size k ; Consider all remaining substrings . We consider every substring ending with index i . ; Print result . ; Driver Code | def getSmallestAndLargest ( s , k ) : NEW_LINE INDENT currStr = s [ : k ] NEW_LINE lexMin = currStr NEW_LINE lexMax = currStr NEW_LINE for i in range ( k , len ( s ) ) : NEW_LINE INDENT currStr = currStr [ 1 : k ] + s [ i ] NEW_LINE if ( lexMax < currStr ) : NEW_LINE INDENT lexMax = currStr NEW_LINE DEDENT if ( lexMin > currStr ) : NEW_LINE INDENT lexMin = currStr NEW_LINE DEDENT DEDENT print ( lexMin ) NEW_LINE print ( lexMax ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT str1 = " GeeksForGeeks " NEW_LINE k = 3 NEW_LINE getSmallestAndLargest ( str1 , k ) NEW_LINE DEDENT |
Program to print the initials of a name with the surname | Python program to print the initials of a name with the surname ; to remove any leading or trailing spaces ; to store extracted words ; forming the word ; when space is encountered it means the name is completed and thereby extracted ; printing the first letter of the name in capital letters ; for the surname , we have to print the entire surname and not just the initial string " t " has the surname now ; first letter of surname in capital letter ; rest of the letters in small ; printing surname ; Driver Code | def printInitials ( string : str ) : NEW_LINE INDENT length = len ( string ) NEW_LINE string . strip ( ) NEW_LINE t = " " NEW_LINE for i in range ( length ) : NEW_LINE INDENT ch = string [ i ] NEW_LINE if ch != ' β ' : NEW_LINE INDENT t += ch NEW_LINE DEDENT else : NEW_LINE INDENT print ( t [ 0 ] . upper ( ) + " . β " , end = " " ) NEW_LINE t = " " NEW_LINE DEDENT DEDENT temp = " " NEW_LINE for j in range ( len ( t ) ) : NEW_LINE INDENT if j == 0 : NEW_LINE INDENT temp += t [ 0 ] . upper ( ) NEW_LINE DEDENT else : NEW_LINE INDENT temp += t [ j ] . lower ( ) NEW_LINE DEDENT DEDENT print ( temp ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT string = " ishita β bhuiya " NEW_LINE printInitials ( string ) NEW_LINE DEDENT |
Count of strings that can be formed from another string using each character at | Python3 program to print the number of times str2 can be formed from str1 using the characters of str1 only once ; Function to find the number of str2 that can be formed using characters of str1 ; iterate and mark the frequencies of all characters in str1 ; find the minimum frequency of every character in str1 ; Driver Code | import sys NEW_LINE def findNumberOfTimes ( str1 , str2 ) : NEW_LINE INDENT freq = [ 0 ] * 26 NEW_LINE l1 = len ( str1 ) NEW_LINE freq2 = [ 0 ] * 26 NEW_LINE l2 = len ( str2 ) NEW_LINE for i in range ( l1 ) : NEW_LINE INDENT freq [ ord ( str1 [ i ] ) - ord ( " a " ) ] += 1 NEW_LINE DEDENT for i in range ( l2 ) : NEW_LINE INDENT freq2 [ ord ( str2 [ i ] ) - ord ( " a " ) ] += 1 NEW_LINE DEDENT count = sys . maxsize NEW_LINE for i in range ( l2 ) : NEW_LINE count = min ( count , freq [ ord ( str2 [ i ] ) - ord ( ' a ' ) ] / freq2 [ ord ( str2 [ i ] ) - ord ( ' a ' ) ] ) NEW_LINE return count NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT str1 = " foreeksgekseg " NEW_LINE str2 = " geeks " NEW_LINE print ( findNumberOfTimes ( str1 , str2 ) ) NEW_LINE DEDENT |
String transformation using XOR and OR | function to check if conversion is possible or not ; if lengths are different ; iterate to check if both strings have 1 ; to check if there is even one 1 in string s1 ; to check if there is even one 1 in string s2 ; if both string do not have a '1' . ; Driver code | def solve ( s1 , s2 ) : NEW_LINE INDENT flag1 = 0 NEW_LINE flag2 = 0 NEW_LINE if ( len ( s1 ) != len ( s2 ) ) : NEW_LINE INDENT return False NEW_LINE DEDENT l = len ( s1 ) NEW_LINE for i in range ( 0 , l ) : NEW_LINE INDENT if ( s1 [ i ] == '1' ) : NEW_LINE INDENT flag1 = 1 ; NEW_LINE DEDENT if ( s2 [ i ] == '1' ) : NEW_LINE INDENT flag2 = 1 NEW_LINE DEDENT if ( flag1 & flag2 ) : NEW_LINE INDENT return True NEW_LINE DEDENT if ( ! flag1 & ! flag2 ) : NEW_LINE INDENT return True NEW_LINE DEDENT DEDENT return False NEW_LINE DEDENT s1 = "100101" NEW_LINE s2 = "100000" NEW_LINE if solve ( s1 , s2 ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT |
Smallest alphabet greater than a given character | Returns the smallest character from the given set of letters that is greater than K ; Take the first element as l and the rightmost element as r ; if this while condition does not satisfy simply return the first element . ; Return the smallest element ; Driver Code ; Function call | def nextGreatestAlphabet ( alphabets , K ) : NEW_LINE INDENT n = len ( alphabets ) NEW_LINE if ( K >= alphabets [ n - 1 ] ) : NEW_LINE return alphabets [ 0 ] NEW_LINE l = 0 NEW_LINE r = len ( alphabets ) - 1 NEW_LINE ans = - 1 NEW_LINE while ( l <= r ) : NEW_LINE INDENT mid = int ( ( l + r ) / 2 ) NEW_LINE if ( alphabets [ mid ] > K ) : NEW_LINE INDENT r = mid - 1 NEW_LINE ans = mid NEW_LINE DEDENT else : NEW_LINE INDENT l = mid + 1 NEW_LINE DEDENT DEDENT if ( alphabets [ ans ] < K ) : NEW_LINE INDENT return alphabets [ 0 ] NEW_LINE DEDENT else : NEW_LINE INDENT return alphabets [ ans ] NEW_LINE DEDENT DEDENT letters = [ ' A ' , ' r ' , ' z ' ] NEW_LINE K = ' z ' NEW_LINE result = nextGreatestAlphabet ( letters , K ) NEW_LINE print ( result ) NEW_LINE |
Longest substring of 0 s in a string formed by k concatenations | Function to calculate maximum length of substring containing only zero ; loop to calculate longest substring in string containing 0 's ; if all elements in string a are '0 ; Else , find prefix and suffix containing only zeroes ; Calculate length of the prefix containing only zeroes ; Calculate length of the suffix containing only zeroes ; if k <= 1 , no need to take suffix + prefix into account ; Driver program to test above function | def subzero ( str , k ) : NEW_LINE INDENT ans = 0 NEW_LINE curr = 0 NEW_LINE n = len ( str ) NEW_LINE for i in str : NEW_LINE INDENT if ( i == '0' ) : NEW_LINE INDENT curr += 1 NEW_LINE DEDENT else : NEW_LINE INDENT curr = 0 NEW_LINE DEDENT ans = max ( ans , curr ) NEW_LINE DEDENT DEDENT ' NEW_LINE INDENT if ( ans == n ) : NEW_LINE INDENT print ( n * k ) NEW_LINE return NEW_LINE DEDENT else : NEW_LINE INDENT pre = suff = 0 NEW_LINE for i in str : NEW_LINE INDENT if ( i == '0' ) : NEW_LINE INDENT pre += 1 NEW_LINE DEDENT else : NEW_LINE INDENT break NEW_LINE DEDENT DEDENT for i in range ( n - 1 , - 1 , - 1 ) : NEW_LINE INDENT if ( str [ i ] == '0' ) : NEW_LINE INDENT suff += 1 NEW_LINE DEDENT else : NEW_LINE INDENT break NEW_LINE DEDENT DEDENT DEDENT if ( k > 1 ) : NEW_LINE INDENT ans = max ( ans , pre + suff ) NEW_LINE DEDENT print ( ans ) NEW_LINE return NEW_LINE DEDENT k = 5 NEW_LINE str = '00100110' NEW_LINE subzero ( str , k ) NEW_LINE |
Find the largest number smaller than integer N with maximum number of set bits | Function to return the largest number less than N ; Iterate through all the numbers ; Find the number of set bits for the current number ; Check if this number has the highest set bits ; Return the result ; Driver code | def largestNum ( n ) : NEW_LINE INDENT num = 0 ; NEW_LINE max_setBits = 0 ; NEW_LINE for i in range ( n + 1 ) : NEW_LINE INDENT setBits = bin ( i ) . count ( '1' ) ; NEW_LINE if ( setBits >= max_setBits ) : NEW_LINE INDENT num = i ; NEW_LINE max_setBits = setBits ; NEW_LINE DEDENT DEDENT return num ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT N = 345 ; NEW_LINE print ( largestNum ( N ) ) ; NEW_LINE DEDENT |
Number of substrings of a string | Python3 program to count number of substrings of a string ; driver code | def countNonEmptySubstr ( str ) : NEW_LINE INDENT n = len ( str ) ; NEW_LINE return int ( n * ( n + 1 ) / 2 ) ; NEW_LINE DEDENT s = " abcde " ; NEW_LINE print ( countNonEmptySubstr ( s ) ) ; NEW_LINE |
Count substrings with each character occurring at most k times | Python 3 program to count number of substrings in which each character has count less than or equal to k . ; variable to store count of substrings . ; array to store count of each character . ; increment character count ; check only the count of current character because only the count of this character is changed . The ending point is incremented to current position only if all other characters have count at most k and hence their count is not checked . If count is less than k , then increase ans by 1. ; if count is less than k , then break as subsequent substrings for this starting point will also have count greater than k and hence are reduntant to check . ; return the final count of substrings . ; Driver code | def findSubstrings ( s , k ) : NEW_LINE INDENT ans = 0 NEW_LINE n = len ( s ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT cnt = [ 0 ] * 26 NEW_LINE for j in range ( i , n ) : NEW_LINE INDENT cnt [ ord ( s [ j ] ) - ord ( ' a ' ) ] += 1 NEW_LINE if ( cnt [ ord ( s [ j ] ) - ord ( ' a ' ) ] <= k ) : NEW_LINE INDENT ans += 1 NEW_LINE DEDENT else : NEW_LINE INDENT break NEW_LINE DEDENT DEDENT DEDENT return ans NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT S = " aaabb " NEW_LINE k = 2 NEW_LINE print ( findSubstrings ( S , k ) ) NEW_LINE DEDENT |
Check if characters of one string can be swapped to form other | Python3 program to check if characters of one string can be swapped to form other ; if length is not same print no ; Count frequencies of character in first string . ; iterate through the second string decrement counts of characters in second string ; Since lengths are same , some value would definitely become negative if result is false . ; Driver Code | MAX = 26 NEW_LINE def targetstring ( str1 , str2 ) : NEW_LINE INDENT l1 = len ( str1 ) NEW_LINE l2 = len ( str2 ) NEW_LINE if ( l1 != l2 ) : NEW_LINE INDENT return False NEW_LINE DEDENT map = [ 0 ] * MAX NEW_LINE for i in range ( l1 ) : NEW_LINE INDENT map [ ord ( str1 [ i ] ) - ord ( ' a ' ) ] += 1 NEW_LINE DEDENT for i in range ( l2 ) : NEW_LINE INDENT map [ ord ( str2 [ i ] ) - ord ( ' a ' ) ] -= 1 NEW_LINE if ( map [ ord ( str2 [ i ] ) - ord ( ' a ' ) ] < 0 ) : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT return True NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT str1 = " geeksforgeeks " NEW_LINE str2 = " geegeeksksfor " NEW_LINE if ( targetstring ( str1 , str2 ) ) : NEW_LINE INDENT print ( " YES " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " NO " ) NEW_LINE DEDENT DEDENT |
Find the Number which contain the digit d | Returns true if d is present as digit in number x . ; Breal loop if d is present as digit ; If loop broke ; function to display the values ; Check all numbers one by one ; checking for digit ; Driver code | def isDigitPresent ( x , d ) : NEW_LINE INDENT while ( x > 0 ) : NEW_LINE INDENT if ( x % 10 == d ) : NEW_LINE INDENT break NEW_LINE DEDENT x = x / 10 NEW_LINE DEDENT return ( x > 0 ) NEW_LINE DEDENT def printNumbers ( n , d ) : NEW_LINE INDENT for i in range ( 0 , n + 1 ) : NEW_LINE INDENT if ( i == d or isDigitPresent ( i , d ) ) : NEW_LINE INDENT print ( i , end = " β " ) NEW_LINE DEDENT DEDENT DEDENT n = 47 NEW_LINE d = 7 NEW_LINE print ( " The β number β of β values β are " ) NEW_LINE printNumbers ( n , d ) NEW_LINE |
Find one extra character in a string | Python3 program to find extra character in one string ; store string values in map ; store second string in map with frequency ; store first string in map with frequency ; if the frequency is 1 then this character is which is added extra ; Driver Code ; given string ; find Extra Character | def findExtraCharacter ( strA , strB ) : NEW_LINE INDENT m1 = { } NEW_LINE for i in strB : NEW_LINE INDENT if i in m1 : NEW_LINE INDENT m1 [ i ] += 1 NEW_LINE DEDENT else : NEW_LINE INDENT m1 [ i ] = 1 NEW_LINE DEDENT DEDENT for i in strA : NEW_LINE INDENT m1 [ i ] -= 1 NEW_LINE DEDENT for h1 in m1 : NEW_LINE INDENT if m1 [ h1 ] == 1 : NEW_LINE INDENT return h1 NEW_LINE DEDENT DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT strA = ' abcd ' NEW_LINE strB = ' cbdad ' NEW_LINE print ( findExtraCharacter ( strA , strB ) ) NEW_LINE DEDENT |
Find one extra character in a string | Python 3 program to find extra character in one string ; result store the result ; traverse string A till end and xor with res ; xor with res ; traverse string B till end and xor with res ; xor with res ; print result at the end ; given string | def findExtraCharcter ( strA , strB ) : NEW_LINE INDENT res = 0 NEW_LINE for i in range ( 0 , len ( strA ) ) : NEW_LINE INDENT res = res ^ ( ord ) ( strA [ i ] ) NEW_LINE DEDENT for i in range ( 0 , len ( strB ) ) : NEW_LINE INDENT res = res ^ ( ord ) ( strB [ i ] ) NEW_LINE DEDENT return ( ( chr ) ( res ) ) ; NEW_LINE DEDENT strA = " abcd " NEW_LINE strB = " cbdad " NEW_LINE print ( findExtraCharcter ( strA , strB ) ) NEW_LINE |
Find one extra character in a string | Python Program to find extra character in one string ; Determine string with extra character ; Add Character codes of both the strings ; Add last character code of large string ; Minus the character code of smaller string from the character code of large string The result will be the extra character code ; Driver code | def findExtraCharacter ( s1 , s2 ) : NEW_LINE INDENT smallStr = " " NEW_LINE largeStr = " " NEW_LINE if ( len ( s1 ) > len ( s2 ) ) : NEW_LINE INDENT smallStr = s2 NEW_LINE largeStr = s1 NEW_LINE DEDENT else : NEW_LINE INDENT smallStr = s1 NEW_LINE largeStr = s2 NEW_LINE DEDENT smallStrCodeTotal = 0 NEW_LINE largeStrCodeTotal = 0 NEW_LINE i = 0 NEW_LINE while ( i < len ( smallStr ) ) : NEW_LINE INDENT smallStrCodeTotal += ord ( smallStr [ i ] ) NEW_LINE largeStrCodeTotal += ord ( largeStr [ i ] ) NEW_LINE i += 1 NEW_LINE DEDENT largeStrCodeTotal += ord ( largeStr [ i ] ) NEW_LINE intChar = largeStrCodeTotal - smallStrCodeTotal NEW_LINE return chr ( intChar ) NEW_LINE DEDENT s1 = " abcd " NEW_LINE s2 = " cbdae " NEW_LINE extraChar = findExtraCharacter ( s1 , s2 ) NEW_LINE print ( " Extra β Character : " , extraChar ) NEW_LINE |
Function to copy string ( Iterative and Recursive ) | Function to copy one string to other ; Driver code | def copy_str ( x , y ) : NEW_LINE INDENT if len ( y ) == 0 : NEW_LINE INDENT return x NEW_LINE DEDENT else : NEW_LINE INDENT c = copy_str ( x , ( y ) [ 1 : - 1 ] ) NEW_LINE return c NEW_LINE DEDENT DEDENT x = input ( ) NEW_LINE y = input ( ) NEW_LINE print ( copy_str ( x , y ) ) NEW_LINE |
Evaluate an array expression with numbers , + and | Function to find the sum of given array ; if string is empty ; stoi function to convert string into integer ; stoi function to convert string into integer ; Find operator ; If operator is equal to ' + ' , add value in sum variable else subtract ; Driver Function | def calculateSum ( arr , n ) : NEW_LINE INDENT if ( n == 0 ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT s = arr [ 0 ] NEW_LINE value = int ( s ) NEW_LINE sum = value NEW_LINE for i in range ( 2 , n , 2 ) : NEW_LINE INDENT s = arr [ i ] NEW_LINE value = int ( s ) NEW_LINE operation = arr [ i - 1 ] [ 0 ] NEW_LINE if ( operation == ' + ' ) : NEW_LINE INDENT sum += value NEW_LINE DEDENT else : NEW_LINE INDENT sum -= value NEW_LINE DEDENT DEDENT return sum NEW_LINE DEDENT arr = [ "3" , " + " , "4" , " - " , "7" , " + " , "13" ] NEW_LINE n = len ( arr ) NEW_LINE print ( calculateSum ( arr , n ) ) NEW_LINE |
String with maximum number of unique characters | Function to find string with maximum number of unique characters . ; Index of string with maximum unique characters ; Iterate through all strings ; Array indicating any alphabet included or not included ; count number of unique alphabets in each string ; keep track of maximum number of alphabets ; print result ; Driver code | def LargestString ( na ) : NEW_LINE INDENT N = len ( na ) NEW_LINE c = [ 0 ] * N NEW_LINE m = 0 NEW_LINE for j in range ( N ) : NEW_LINE INDENT character = [ False ] * 26 NEW_LINE for k in range ( len ( na [ j ] ) ) : NEW_LINE INDENT x = ord ( na [ j ] [ k ] ) - ord ( ' A ' ) NEW_LINE if ( ( na [ j ] [ k ] != ' β ' ) and ( character [ x ] == False ) ) : NEW_LINE INDENT c [ j ] += 1 NEW_LINE character [ x ] = True NEW_LINE DEDENT if ( c [ j ] > c [ m ] ) : NEW_LINE INDENT m = j NEW_LINE DEDENT DEDENT DEDENT print ( na [ m ] ) NEW_LINE DEDENT na = [ " BOB " , " A β AB β C β JOHNSON " , " ANJALI " , " ASKRIT " , " ARMAN β MALLIK " ] NEW_LINE LargestString ( na ) NEW_LINE |
Program for length of the longest word in a sentence | Python program to find the number of characters in the longest word in the sentence . ; Driver Code | def longestWordLength ( string ) : NEW_LINE INDENT length = 0 NEW_LINE for word in string . split ( ) : NEW_LINE INDENT if ( len ( word ) > length ) : NEW_LINE INDENT length = len ( word ) NEW_LINE DEDENT DEDENT return length NEW_LINE DEDENT string = " I β am β an β intern β at β geeksforgeeks " NEW_LINE print ( longestWordLength ( string ) ) NEW_LINE |
Morse Code Implementation | function to encode a alphabet as Morse code ; refer to the Morse table image attached in the article ; for space ; character by character print Morse code ; Driver Code | def morseEncode ( x ) : NEW_LINE INDENT if x is ' a ' : NEW_LINE INDENT return " . - " NEW_LINE DEDENT elif x is ' b ' : NEW_LINE INDENT return " - . . . " NEW_LINE DEDENT elif x is ' c ' : NEW_LINE INDENT return " - . - . " NEW_LINE DEDENT elif x is ' d ' : NEW_LINE INDENT return " - . . " NEW_LINE DEDENT elif x is ' e ' : NEW_LINE INDENT return " . " NEW_LINE DEDENT elif x is ' f ' : NEW_LINE INDENT return " . . - . " NEW_LINE DEDENT elif x is ' g ' : NEW_LINE INDENT return " - - . " NEW_LINE DEDENT elif x is ' h ' : NEW_LINE INDENT return " . . . . " NEW_LINE DEDENT elif x is ' i ' : NEW_LINE INDENT return " . . " NEW_LINE DEDENT elif x is ' j ' : NEW_LINE INDENT return " . - - - " NEW_LINE DEDENT elif x is ' k ' : NEW_LINE INDENT return " - . - " NEW_LINE DEDENT elif x is ' l ' : NEW_LINE INDENT return " . - . . " NEW_LINE DEDENT elif x is ' m ' : NEW_LINE INDENT return " - - " NEW_LINE DEDENT elif x is ' n ' : NEW_LINE INDENT return " - . " NEW_LINE DEDENT elif x is ' o ' : NEW_LINE INDENT return " - - - " NEW_LINE DEDENT elif x is ' p ' : NEW_LINE INDENT return " . - - . " NEW_LINE DEDENT elif x is ' q ' : NEW_LINE INDENT return " - - . - " NEW_LINE DEDENT elif x is ' r ' : NEW_LINE INDENT return " . - . " NEW_LINE DEDENT elif x is ' s ' : NEW_LINE INDENT return " . . . " NEW_LINE DEDENT elif x is ' t ' : NEW_LINE INDENT return " - " NEW_LINE DEDENT elif x is ' u ' : NEW_LINE INDENT return " . . - " NEW_LINE DEDENT elif x is ' v ' : NEW_LINE INDENT return " . . . - " NEW_LINE DEDENT elif x is ' w ' : NEW_LINE INDENT return " . - - " NEW_LINE DEDENT elif x is ' x ' : NEW_LINE INDENT return " - . . - " NEW_LINE DEDENT elif x is ' y ' : NEW_LINE INDENT return " - . - - " NEW_LINE DEDENT elif x is ' z ' : NEW_LINE INDENT return " - - . . " NEW_LINE DEDENT elif x is '1' : NEW_LINE INDENT return " . - - - - " ; NEW_LINE DEDENT elif x is '2' : NEW_LINE INDENT return " . . - - - " ; NEW_LINE DEDENT elif x is '3' : NEW_LINE INDENT return " . . . - - " ; NEW_LINE DEDENT elif x is '4' : NEW_LINE INDENT return " . . . . - " ; NEW_LINE DEDENT elif x is '5' : NEW_LINE INDENT return " . . . . . " ; NEW_LINE DEDENT elif x is '6' : NEW_LINE INDENT return " - . . . . " ; NEW_LINE DEDENT elif x is '7' : NEW_LINE INDENT return " - - . . . " ; NEW_LINE DEDENT elif x is '8' : NEW_LINE INDENT return " - - - . . " ; NEW_LINE DEDENT elif x is '9' : NEW_LINE INDENT return " - - - - . " ; NEW_LINE DEDENT elif x is '0' : NEW_LINE INDENT return " - - - - - " ; NEW_LINE DEDENT DEDENT def morseCode ( s ) : NEW_LINE INDENT for character in s : NEW_LINE INDENT print ( morseEncode ( character ) , end = " " ) NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT s = " geeksforgeeks " NEW_LINE morseCode ( s ) NEW_LINE DEDENT |
Polybius Square Cipher | function to display polybius cipher text ; convert each character to its encrypted code ; finding row of the table ; finding column of the table ; if character is 'k ; if character is greater than 'j ; Driver 's Code ; print the cipher of " geeksforgeeks " | def polybiusCipher ( s ) : NEW_LINE INDENT for char in s : NEW_LINE INDENT row = int ( ( ord ( char ) - ord ( ' a ' ) ) / 5 ) + 1 NEW_LINE col = ( ( ord ( char ) - ord ( ' a ' ) ) % 5 ) + 1 NEW_LINE DEDENT DEDENT ' NEW_LINE INDENT if char == ' k ' : NEW_LINE INDENT row = row - 1 NEW_LINE col = 5 - col + 1 NEW_LINE DEDENT DEDENT ' NEW_LINE INDENT elif ord ( char ) >= ord ( ' j ' ) : NEW_LINE INDENT if col == 1 : NEW_LINE INDENT col = 6 NEW_LINE row = row - 1 NEW_LINE DEDENT col = col - 1 NEW_LINE DEDENT print ( row , col , end = ' ' , sep = ' ' ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT s = " geeksforgeeks " NEW_LINE polybiusCipher ( s ) NEW_LINE DEDENT |
Minimum removal to make palindrome permutation | function to find minimum removal of characters ; hash to store frequency of each character to set hash array to zeros ; count frequency of each character ; count the odd frequency characters ; if count is 0 , return 0 otherwise return count ; Driver 's Code | def minRemoval ( strr ) : NEW_LINE INDENT hash = [ 0 ] * 26 NEW_LINE for char in strr : NEW_LINE INDENT hash [ ord ( char ) - ord ( ' a ' ) ] = hash [ ord ( char ) - ord ( ' a ' ) ] + 1 NEW_LINE DEDENT count = 0 NEW_LINE for i in range ( 26 ) : NEW_LINE INDENT if hash [ i ] % 2 : NEW_LINE INDENT count = count + 1 NEW_LINE DEDENT DEDENT return 0 if count == 0 else count - 1 NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT strr = " geeksforgeeks " ; NEW_LINE DEDENT |
Union | Python3 program to implement Union - Find with union by rank and path compression . ; Arr to represent parent of index i ; Size to represent the number of nodes in subgxrph rooted at index i ; set parent of every node to itself and size of node to one ; Each time we follow a path , find function compresses it further until the path length is greater than or equal to 1. ; while we reach a node whose parent is equal to itself ; Skip one level ; Move to the new level ; A function that does union of two nodes x and y where xr is root node of x and yr is root node of y ; Make yr parent of xr ; Make xr parent of yr ; The main function to check whether a given graph contains cycle or not ; Itexrte through all edges of gxrph , find nodes connecting them . If root nodes of both are same , then there is cycle in gxrph . ; find root of i ; find root of adj [ i ] [ j ] ; If same parent ; Make them connect ; Driver Code ; Initialize the values for arxry Arr and Size ; Adjacency list for graph ; call is_cycle to check if it contains cycle | MAX_VERTEX = 101 NEW_LINE Arr = [ None ] * MAX_VERTEX NEW_LINE size = [ None ] * MAX_VERTEX NEW_LINE def initialize ( n ) : NEW_LINE INDENT global Arr , size NEW_LINE for i in range ( n + 1 ) : NEW_LINE INDENT Arr [ i ] = i NEW_LINE size [ i ] = 1 NEW_LINE DEDENT DEDENT def find ( i ) : NEW_LINE INDENT global Arr , size NEW_LINE while ( Arr [ i ] != i ) : NEW_LINE INDENT Arr [ i ] = Arr [ Arr [ i ] ] NEW_LINE i = Arr [ i ] NEW_LINE DEDENT return i NEW_LINE DEDENT def _union ( xr , yr ) : NEW_LINE INDENT global Arr , size NEW_LINE DEDENT if ( size [ xr ] < size [ yr ] ) : NEW_LINE INDENT Arr [ xr ] = Arr [ yr ] NEW_LINE size [ yr ] += size [ xr ] NEW_LINE DEDENT else : NEW_LINE INDENT Arr [ yr ] = Arr [ xr ] NEW_LINE size [ xr ] += size [ yr ] NEW_LINE DEDENT def isCycle ( adj , V ) : NEW_LINE INDENT global Arr , size NEW_LINE for i in range ( V ) : NEW_LINE INDENT for j in range ( len ( adj [ i ] ) ) : NEW_LINE DEDENT DEDENT x = find ( i ) NEW_LINE y = find ( adj [ i ] [ j ] ) NEW_LINE INDENT if ( x == y ) : NEW_LINE DEDENT return 1 NEW_LINE _union ( x , y ) NEW_LINE INDENT return 0 NEW_LINE DEDENT V = 3 NEW_LINE initialize ( V ) NEW_LINE adj = [ [ ] for i in range ( V ) ] NEW_LINE adj [ 0 ] . append ( 1 ) NEW_LINE adj [ 0 ] . append ( 2 ) NEW_LINE adj [ 1 ] . append ( 2 ) NEW_LINE if ( isCycle ( adj , V ) ) : NEW_LINE INDENT print ( " Graph β contains β Cycle . " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " Graph β does β not β contain β Cycle . " ) NEW_LINE DEDENT |
Queries for frequencies of characters in substrings | Python3 program to find occurrence of character in substring l to r ; To store count of all character ; To pre - process string from 0 to size of string ; Store occurrence of character i ; Store occurrence o all character upto i ; To return occurrence of character in range l to r ; Return occurrence of character from 0 to r minus its occurrence from 0 to l ; Driver Code | MAX_LEN , MAX_CHAR = 1005 , 26 NEW_LINE cnt = [ [ 0 for i in range ( MAX_CHAR ) ] for j in range ( MAX_LEN ) ] NEW_LINE def preProcess ( s ) : NEW_LINE INDENT n = len ( s ) NEW_LINE for i in range ( 0 , n ) : NEW_LINE INDENT cnt [ i ] [ ord ( s [ i ] ) - ord ( ' a ' ) ] += 1 NEW_LINE DEDENT for i in range ( 1 , n ) : NEW_LINE INDENT for j in range ( 0 , 26 ) : NEW_LINE INDENT cnt [ i ] [ j ] += cnt [ i - 1 ] [ j ] NEW_LINE DEDENT DEDENT DEDENT def findCharFreq ( l , r , c ) : NEW_LINE INDENT return ( cnt [ r ] [ ord ( c ) - 97 ] - cnt [ l - 1 ] [ ord ( c ) - 97 ] ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT s = " geeksforgeeks " NEW_LINE Q = 4 NEW_LINE preProcess ( s ) NEW_LINE print ( findCharFreq ( 0 , 5 , ' e ' ) ) NEW_LINE print ( findCharFreq ( 2 , 6 , ' f ' ) ) NEW_LINE print ( findCharFreq ( 4 , 7 , ' m ' ) ) NEW_LINE print ( findCharFreq ( 0 , 12 , ' e ' ) ) NEW_LINE DEDENT |
Longest Uncommon Subsequence | Python program to find longest uncommon subsequence using naive method ; function to calculate length of longest uncommon subsequence ; Case 1 : If strings are equal ; for case 2 and case 3 ; input strings | import math NEW_LINE def findLUSlength ( a , b ) : NEW_LINE INDENT if ( a == b ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT return max ( len ( a ) , len ( b ) ) NEW_LINE DEDENT a = " abcdabcd " NEW_LINE b = " abcabc " NEW_LINE print ( findLUSlength ( a , b ) ) NEW_LINE |
Interchanging first and second halves of strings | Function to concatenate two different halves of given strings ; Creating new strings by exchanging the first half of a and b . Please refer below for details of substr . https : www . geeksforgeeks . org / stdsubstr - in - ccpp / ; Driver function ; | def swapTwoHalves ( a , b ) : NEW_LINE INDENT la = len ( a ) NEW_LINE lb = len ( b ) NEW_LINE c = a [ 0 : la // 2 ] + b [ lb // 2 : lb ] NEW_LINE d = b [ 0 : lb // 2 ] + a [ la // 2 : la ] NEW_LINE print ( c , " " , d ) NEW_LINE DEDENT a = " remuneration " NEW_LINE b = " day " NEW_LINE / * Calling function * / NEW_LINE swapTwoHalves ( a , b ) NEW_LINE |
Magical Indices in an array | Function to count number of magical indices . ; Array to store parent node of traversal . ; Array to determine whether current node is already counted in the cycle . ; Initialize the arrays . ; Check if current node is already traversed or not . If node is not traversed yet then parent value will be - 1. ; Traverse the graph until an already visited node is not found . ; Check parent value to ensure a cycle is present . ; Count number of nodes in the cycle . ; Driver code | def solve ( A , n ) : NEW_LINE INDENT cnt = 0 NEW_LINE parent = [ None ] * ( n + 1 ) NEW_LINE vis = [ None ] * ( n + 1 ) NEW_LINE for i in range ( 0 , n + 1 ) : NEW_LINE INDENT parent [ i ] = - 1 NEW_LINE vis [ i ] = 0 NEW_LINE DEDENT for i in range ( 0 , n ) : NEW_LINE INDENT j = i NEW_LINE if ( parent [ j ] == - 1 ) : NEW_LINE INDENT while ( parent [ j ] == - 1 ) : NEW_LINE INDENT parent [ j ] = i NEW_LINE j = ( j + A [ j ] + 1 ) % n NEW_LINE DEDENT if ( parent [ j ] == i ) : NEW_LINE INDENT while ( vis [ j ] == 0 ) : NEW_LINE INDENT vis [ j ] = 1 NEW_LINE cnt = cnt + 1 NEW_LINE j = ( j + A [ j ] + 1 ) % n NEW_LINE DEDENT DEDENT DEDENT DEDENT return cnt NEW_LINE DEDENT A = [ 0 , 0 , 0 , 2 ] NEW_LINE n = len ( A ) NEW_LINE print ( solve ( A , n ) ) NEW_LINE |
Longest path between any pair of vertices | visited [ ] array to make nodes visited src is starting node for DFS traversal prev_len is sum of cable length till current node max_len is pointer which stores the maximum length of cable value after DFS traversal ; Mark the src node visited ; curr_len is for length of cable from src city to its adjacent city ; Adjacent is pair type which stores destination city and cable length ; Traverse all adjacent ; Adjacent element ; If node or city is not visited ; Total length of cable from src city to its adjacent ; Call DFS for adjacent city ; If total cable length till now greater than previous length then update it ; make curr_len = 0 for next adjacent ; n is number of cities or nodes in graph cable_lines is total cable_lines among the cities or edges in graph ; maximum length of cable among the connected cities ; call DFS for each city to find maximum length of cable ; initialize visited array with 0 ; Call DFS for src vertex i ; Driver Code ; n is number of cities ; create undirected graph first edge ; second edge ; third edge ; fourth edge ; fifth edge | def DFS ( graph , src , prev_len , max_len , visited ) : NEW_LINE INDENT visited [ src ] = 1 NEW_LINE curr_len = 0 NEW_LINE adjacent = None NEW_LINE for i in range ( len ( graph [ src ] ) ) : NEW_LINE INDENT adjacent = graph [ src ] [ i ] NEW_LINE if ( not visited [ adjacent [ 0 ] ] ) : NEW_LINE INDENT curr_len = prev_len + adjacent [ 1 ] NEW_LINE DFS ( graph , adjacent [ 0 ] , curr_len , max_len , visited ) NEW_LINE DEDENT if ( max_len [ 0 ] < curr_len ) : NEW_LINE INDENT max_len [ 0 ] = curr_len NEW_LINE DEDENT curr_len = 0 NEW_LINE DEDENT DEDENT def longestCable ( graph , n ) : NEW_LINE INDENT max_len = [ - 999999999999 ] NEW_LINE for i in range ( 1 , n + 1 ) : NEW_LINE INDENT visited = [ False ] * ( n + 1 ) NEW_LINE DFS ( graph , i , 0 , max_len , visited ) NEW_LINE DEDENT return max_len [ 0 ] NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT n = 6 NEW_LINE graph = [ [ ] for i in range ( n + 1 ) ] NEW_LINE graph [ 1 ] . append ( [ 2 , 3 ] ) NEW_LINE graph [ 2 ] . append ( [ 1 , 3 ] ) NEW_LINE graph [ 2 ] . append ( [ 3 , 4 ] ) NEW_LINE graph [ 3 ] . append ( [ 2 , 4 ] ) NEW_LINE graph [ 2 ] . append ( [ 6 , 2 ] ) NEW_LINE graph [ 6 ] . append ( [ 2 , 2 ] ) NEW_LINE graph [ 4 ] . append ( [ 6 , 6 ] ) NEW_LINE graph [ 6 ] . append ( [ 4 , 6 ] ) NEW_LINE graph [ 5 ] . append ( [ 6 , 5 ] ) NEW_LINE graph [ 6 ] . append ( [ 5 , 5 ] ) NEW_LINE print ( " Maximum β length β of β cable β = " , longestCable ( graph , n ) ) NEW_LINE DEDENT |
Level order traversal with direction change after every two levels | A Binary Tree Node ; Function to prthe level order of given binary tree . Direction of printing level order traversal of binary tree changes after every two levels ; For null root ; Maintain a queue for normal level order traversal ; Maintain a stack for printing nodes in reverse order after they are popped out from queue . ; sz is used for storing the count of nodes in a level ; Used for changing the direction of level order traversal ; Used for changing the direction of level order traversal ; Push root node to the queue ; Run this while loop till queue got empty ; Do a normal level order traversal ; For printing nodes from left to right , simply prthe nodes in the order in which they are being popped out from the queue . ; For printing nodes from right to left , push the nodes to stack instead of printing them . ; for printing the nodes in order from right to left ; Change the direction of printing nodes after every two levels . ; Driver program to test above functions ; Let us create binary tree | from collections import deque NEW_LINE class Node : NEW_LINE INDENT def __init__ ( self , x ) : NEW_LINE INDENT self . data = x NEW_LINE self . left = None NEW_LINE self . right = None NEW_LINE DEDENT DEDENT def modifiedLevelOrder ( node ) : NEW_LINE INDENT if ( node == None ) : NEW_LINE INDENT return NEW_LINE DEDENT if ( node . left == None and node . right == None ) : NEW_LINE INDENT print ( node . data , end = " β " ) NEW_LINE return NEW_LINE DEDENT myQueue = deque ( ) NEW_LINE myStack = [ ] NEW_LINE temp = None NEW_LINE sz = 0 NEW_LINE ct = 0 NEW_LINE rightToLeft = False NEW_LINE myQueue . append ( node ) NEW_LINE while ( len ( myQueue ) > 0 ) : NEW_LINE INDENT ct += 1 NEW_LINE sz = len ( myQueue ) NEW_LINE for i in range ( sz ) : NEW_LINE INDENT temp = myQueue . popleft ( ) NEW_LINE if ( rightToLeft == False ) : NEW_LINE INDENT print ( temp . data , end = " β " ) NEW_LINE DEDENT else : NEW_LINE INDENT myStack . append ( temp ) NEW_LINE DEDENT if ( temp . left ) : NEW_LINE INDENT myQueue . append ( temp . left ) NEW_LINE DEDENT if ( temp . right ) : NEW_LINE INDENT myQueue . append ( temp . right ) NEW_LINE DEDENT DEDENT if ( rightToLeft == True ) : NEW_LINE INDENT while ( len ( myStack ) > 0 ) : NEW_LINE INDENT temp = myStack [ - 1 ] NEW_LINE del myStack [ - 1 ] NEW_LINE print ( temp . data , end = " β " ) NEW_LINE DEDENT DEDENT if ( ct == 2 ) : NEW_LINE INDENT rightToLeft = not rightToLeft NEW_LINE ct = 0 NEW_LINE DEDENT print ( ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT root = Node ( 1 ) NEW_LINE root . left = Node ( 2 ) NEW_LINE root . right = Node ( 3 ) NEW_LINE root . left . left = Node ( 4 ) NEW_LINE root . left . right = Node ( 5 ) NEW_LINE root . right . left = Node ( 6 ) NEW_LINE root . right . right = Node ( 7 ) NEW_LINE root . left . left . left = Node ( 8 ) NEW_LINE root . left . left . right = Node ( 9 ) NEW_LINE root . left . right . left = Node ( 3 ) NEW_LINE root . left . right . right = Node ( 1 ) NEW_LINE root . right . left . left = Node ( 4 ) NEW_LINE root . right . left . right = Node ( 2 ) NEW_LINE root . right . right . left = Node ( 7 ) NEW_LINE root . right . right . right = Node ( 2 ) NEW_LINE root . left . right . left . left = Node ( 16 ) NEW_LINE root . left . right . left . right = Node ( 17 ) NEW_LINE root . right . left . right . left = Node ( 18 ) NEW_LINE root . right . right . left . right = Node ( 19 ) NEW_LINE modifiedLevelOrder ( root ) NEW_LINE DEDENT |
Minimum cost to connect all cities | Function to find out minimum valued node among the nodes which are not yet included in MST ; Loop through all the values of the nodes which are not yet included in MST and find the minimum valued one . ; Function to find out the MST and the cost of the MST . ; Array to store the parent node of a particular node . ; Array to store key value of each node . ; Boolean Array to hold bool values whether a node is included in MST or not . ; Set all the key values to infinite and none of the nodes is included in MST . ; Start to find the MST from node 0. Parent of node 0 is none so set - 1. key value or minimum cost to reach 0 th node from 0 th node is 0. ; Find the rest n - 1 nodes of MST . ; First find out the minimum node among the nodes which are not yet included in MST . ; Now the uth node is included in MST . ; Update the values of neighbor nodes of u which are not yet included in MST . ; Find out the cost by adding the edge values of MST . ; Driver Code ; Input 1 ; Input 2 | def minnode ( n , keyval , mstset ) : NEW_LINE INDENT mini = 999999999999 NEW_LINE mini_index = None NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( mstset [ i ] == False and keyval [ i ] < mini ) : NEW_LINE INDENT mini = keyval [ i ] NEW_LINE mini_index = i NEW_LINE DEDENT DEDENT return mini_index NEW_LINE DEDENT def findcost ( n , city ) : NEW_LINE INDENT parent = [ None ] * n NEW_LINE keyval = [ None ] * n NEW_LINE mstset = [ None ] * n NEW_LINE for i in range ( n ) : NEW_LINE INDENT keyval [ i ] = 9999999999999 NEW_LINE mstset [ i ] = False NEW_LINE DEDENT parent [ 0 ] = - 1 NEW_LINE keyval [ 0 ] = 0 NEW_LINE for i in range ( n - 1 ) : NEW_LINE INDENT u = minnode ( n , keyval , mstset ) NEW_LINE mstset [ u ] = True NEW_LINE for v in range ( n ) : NEW_LINE INDENT if ( city [ u ] [ v ] and mstset [ v ] == False and city [ u ] [ v ] < keyval [ v ] ) : NEW_LINE INDENT keyval [ v ] = city [ u ] [ v ] NEW_LINE parent [ v ] = u NEW_LINE DEDENT DEDENT DEDENT cost = 0 NEW_LINE for i in range ( 1 , n ) : NEW_LINE INDENT cost += city [ parent [ i ] ] [ i ] NEW_LINE DEDENT print ( cost ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT n1 = 5 NEW_LINE city1 = [ [ 0 , 1 , 2 , 3 , 4 ] , [ 1 , 0 , 5 , 0 , 7 ] , [ 2 , 5 , 0 , 6 , 0 ] , [ 3 , 0 , 6 , 0 , 0 ] , [ 4 , 7 , 0 , 0 , 0 ] ] NEW_LINE findcost ( n1 , city1 ) NEW_LINE n2 = 6 NEW_LINE city2 = [ [ 0 , 1 , 1 , 100 , 0 , 0 ] , [ 1 , 0 , 1 , 0 , 0 , 0 ] , [ 1 , 1 , 0 , 0 , 0 , 0 ] , [ 100 , 0 , 0 , 0 , 2 , 2 ] , [ 0 , 0 , 0 , 2 , 0 , 2 ] , [ 0 , 0 , 0 , 2 , 2 , 0 ] ] NEW_LINE findcost ( n2 , city2 ) NEW_LINE DEDENT |
Minimum Product Spanning Tree | A Python3 program for getting minimum product spanning tree The program is for adjacency matrix representation of the graph ; Number of vertices in the graph ; A utility function to find the vertex with minimum key value , from the set of vertices not yet included in MST ; Initialize min value ; A utility function to print the constructed MST stored in parent [ ] and print Minimum Obtaiable product ; Function to construct and print MST for a graph represented using adjacency matrix representation inputGraph is sent for printing actual edges and logGraph is sent for actual MST operations ; Array to store constructed MST ; Key values used to pick minimum ; weight edge in cut To represent set of vertices not ; Always include first 1 st vertex in MST Make key 0 so that this vertex is ; Picked as first vertex First node is always root of MST ; The MST will have V vertices ; Pick the minimum key vertex from the set of vertices not yet included in MST ; Add the picked vertex to the MST Set ; Update key value and parent index of the adjacent vertices of the picked vertex . Consider only those vertices which are not yet included in MST ; logGraph [ u ] [ v ] is non zero only for adjacent vertices of m mstSet [ v ] is false for vertices not yet included in MST . Update the key only if logGraph [ u ] [ v ] is smaller than key [ v ] ; Print the constructed MST ; Method to get minimum product spanning tree ; Constructing logGraph from original graph ; Applyting standard Prim 's MST algorithm on Log graph. ; Driver code ; Let us create the following graph 2 3 ( 0 ) -- ( 1 ) -- ( 2 ) | / \ | 6 | 8 / \ 5 | 7 | / \ | ( 3 ) -- -- -- - ( 4 ) 9 ; Print the solution | import math NEW_LINE V = 5 NEW_LINE def minKey ( key , mstSet ) : NEW_LINE INDENT min = 10000000 NEW_LINE min_index = 0 NEW_LINE for v in range ( V ) : NEW_LINE INDENT if ( mstSet [ v ] == False and key [ v ] < min ) : NEW_LINE INDENT min = key [ v ] NEW_LINE min_index = v NEW_LINE DEDENT DEDENT return min_index NEW_LINE DEDENT def printMST ( parent , n , graph ) : NEW_LINE INDENT print ( " Edge β Weight " ) NEW_LINE minProduct = 1 NEW_LINE for i in range ( 1 , V ) : NEW_LINE INDENT print ( " { } β - β { } β { } β " . format ( parent [ i ] , i , graph [ i ] [ parent [ i ] ] ) ) NEW_LINE minProduct *= graph [ i ] [ parent [ i ] ] NEW_LINE DEDENT print ( " Minimum β Obtainable β product β is β { } " . format ( minProduct ) ) NEW_LINE DEDENT def primMST ( inputGraph , logGraph ) : NEW_LINE INDENT parent = [ 0 for i in range ( V ) ] NEW_LINE key = [ 10000000 for i in range ( V ) ] NEW_LINE mstSet = [ False for i in range ( V ) ] NEW_LINE key [ 0 ] = 0 NEW_LINE parent [ 0 ] = - 1 NEW_LINE for count in range ( 0 , V - 1 ) : NEW_LINE INDENT u = minKey ( key , mstSet ) NEW_LINE mstSet [ u ] = True NEW_LINE for v in range ( V ) : NEW_LINE INDENT if ( logGraph [ u ] [ v ] > 0 and mstSet [ v ] == False and logGraph [ u ] [ v ] < key [ v ] ) : NEW_LINE INDENT parent [ v ] = u NEW_LINE key [ v ] = logGraph [ u ] [ v ] NEW_LINE DEDENT DEDENT DEDENT printMST ( parent , V , inputGraph ) NEW_LINE DEDENT def minimumProductMST ( graph ) : NEW_LINE INDENT logGraph = [ [ 0 for j in range ( V ) ] for i in range ( V ) ] NEW_LINE for i in range ( V ) : NEW_LINE INDENT for j in range ( V ) : NEW_LINE INDENT if ( graph [ i ] [ j ] > 0 ) : NEW_LINE INDENT logGraph [ i ] [ j ] = math . log ( graph [ i ] [ j ] ) NEW_LINE DEDENT else : NEW_LINE INDENT logGraph [ i ] [ j ] = 0 NEW_LINE DEDENT DEDENT DEDENT primMST ( graph , logGraph ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT graph = [ [ 0 , 2 , 0 , 6 , 0 ] , [ 2 , 0 , 3 , 8 , 5 ] , [ 0 , 3 , 0 , 0 , 7 ] , [ 6 , 8 , 0 , 0 , 9 ] , [ 0 , 5 , 7 , 9 , 0 ] , ] NEW_LINE minimumProductMST ( graph ) NEW_LINE DEDENT |
Insertion in a Binary Tree in level order | A binary tree node has key , pointer to left child and a pointer to right child ; Inorder traversal of a binary tree ; function to insert element in binary tree ; Do level order traversal until we find an empty place . ; Driver code | class newNode ( ) : NEW_LINE INDENT def __init__ ( self , data ) : NEW_LINE INDENT self . key = data NEW_LINE self . left = None NEW_LINE self . right = None NEW_LINE DEDENT DEDENT def inorder ( temp ) : NEW_LINE INDENT if ( not temp ) : NEW_LINE INDENT return NEW_LINE DEDENT inorder ( temp . left ) NEW_LINE print ( temp . key , end = " β " ) NEW_LINE inorder ( temp . right ) NEW_LINE DEDENT def insert ( temp , key ) : NEW_LINE INDENT if not temp : NEW_LINE INDENT root = newNode ( key ) NEW_LINE return NEW_LINE DEDENT q = [ ] NEW_LINE q . append ( temp ) NEW_LINE while ( len ( q ) ) : NEW_LINE INDENT temp = q [ 0 ] NEW_LINE q . pop ( 0 ) NEW_LINE if ( not temp . left ) : NEW_LINE INDENT temp . left = newNode ( key ) NEW_LINE break NEW_LINE DEDENT else : NEW_LINE INDENT q . append ( temp . left ) NEW_LINE DEDENT if ( not temp . right ) : NEW_LINE INDENT temp . right = newNode ( key ) NEW_LINE break NEW_LINE DEDENT else : NEW_LINE INDENT q . append ( temp . right ) NEW_LINE DEDENT DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT root = newNode ( 10 ) NEW_LINE root . left = newNode ( 11 ) NEW_LINE root . left . left = newNode ( 7 ) NEW_LINE root . right = newNode ( 9 ) NEW_LINE root . right . left = newNode ( 15 ) NEW_LINE root . right . right = newNode ( 8 ) NEW_LINE print ( " Inorder β traversal β before β insertion : " , end = " β " ) NEW_LINE inorder ( root ) NEW_LINE key = 12 NEW_LINE insert ( root , key ) NEW_LINE print ( ) NEW_LINE print ( " Inorder β traversal β after β insertion : " , end = " β " ) NEW_LINE inorder ( root ) NEW_LINE DEDENT |
Tug of War | function that tries every possible solution by calling itself recursively ; checks whether the it is going out of bound ; checks that the numbers of elements left are not less than the number of elements required to form the solution ; consider the cases when current element is not included in the solution ; add the current element to the solution ; checks if a solution is formed ; checks if the solution formed is better than the best solution so far ; consider the cases where current element is included in the solution ; removes current element before returning to the caller of this function ; main function that generate an arr ; the boolean array that contains the inclusion and exclusion of an element in current set . The number excluded automatically form the other set ; The inclusion / exclusion array for final solution ; Find the solution using recursive function TOWUtil ( ) ; Print the solution ; Driver Code | def TOWUtil ( arr , n , curr_elements , no_of_selected_elements , soln , min_diff , Sum , curr_sum , curr_position ) : NEW_LINE INDENT if ( curr_position == n ) : NEW_LINE INDENT return NEW_LINE DEDENT if ( ( int ( n / 2 ) - no_of_selected_elements ) > ( n - curr_position ) ) : NEW_LINE INDENT return NEW_LINE DEDENT TOWUtil ( arr , n , curr_elements , no_of_selected_elements , soln , min_diff , Sum , curr_sum , curr_position + 1 ) NEW_LINE no_of_selected_elements += 1 NEW_LINE curr_sum = curr_sum + arr [ curr_position ] NEW_LINE curr_elements [ curr_position ] = True NEW_LINE if ( no_of_selected_elements == int ( n / 2 ) ) : NEW_LINE INDENT if ( abs ( int ( Sum / 2 ) - curr_sum ) < min_diff [ 0 ] ) : NEW_LINE INDENT min_diff [ 0 ] = abs ( int ( Sum / 2 ) - curr_sum ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT soln [ i ] = curr_elements [ i ] NEW_LINE DEDENT DEDENT DEDENT else : NEW_LINE INDENT TOWUtil ( arr , n , curr_elements , no_of_selected_elements , soln , min_diff , Sum , curr_sum , curr_position + 1 ) NEW_LINE DEDENT curr_elements [ curr_position ] = False NEW_LINE DEDENT def tugOfWar ( arr , n ) : NEW_LINE INDENT curr_elements = [ None ] * n NEW_LINE soln = [ None ] * n NEW_LINE min_diff = [ 999999999999 ] NEW_LINE Sum = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT Sum += arr [ i ] NEW_LINE curr_elements [ i ] = soln [ i ] = False NEW_LINE DEDENT TOWUtil ( arr , n , curr_elements , 0 , soln , min_diff , Sum , 0 , 0 ) NEW_LINE print ( " The β first β subset β is : β " ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( soln [ i ] == True ) : NEW_LINE INDENT print ( arr [ i ] , end = " β " ) NEW_LINE DEDENT DEDENT print ( ) NEW_LINE print ( " The β second β subset β is : β " ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( soln [ i ] == False ) : NEW_LINE INDENT print ( arr [ i ] , end = " β " ) NEW_LINE DEDENT DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 23 , 45 , - 34 , 12 , 0 , 98 , - 99 , 4 , 189 , - 1 , 4 ] NEW_LINE n = len ( arr ) NEW_LINE tugOfWar ( arr , n ) NEW_LINE DEDENT |
The Knight 's tour problem | Backtracking | Python3 program to solve Knight Tour problem using Backtracking Chessboard Size ; A utility function to check if i , j are valid indexes for N * N chessboard ; A utility function to print Chessboard matrix ; This function solves the Knight Tour problem using Backtracking . This function mainly uses solveKTUtil ( ) to solve the problem . It returns false if no complete tour is possible , otherwise return true and prints the tour . Please note that there may be more than one solutions , this function prints one of the feasible solutions . ; Initialization of Board matrix ; move_x and move_y define next move of Knight . move_x is for next value of x coordinate move_y is for next value of y coordinate ; Since the Knight is initially at the first block ; Checking if solution exists or not ; A recursive utility function to solve Knight Tour problem ; Try all next moves from the current coordinate x , y ; Backtracking ; Driver Code ; Function Call | n = 8 NEW_LINE def isSafe ( x , y , board ) : NEW_LINE INDENT if ( x >= 0 and y >= 0 and x < n and y < n and board [ x ] [ y ] == - 1 ) : NEW_LINE INDENT return True NEW_LINE DEDENT return False NEW_LINE DEDENT def printSolution ( n , board ) : NEW_LINE INDENT for i in range ( n ) : NEW_LINE INDENT for j in range ( n ) : NEW_LINE INDENT print ( board [ i ] [ j ] , end = ' β ' ) NEW_LINE DEDENT print ( ) NEW_LINE DEDENT DEDENT def solveKT ( n ) : NEW_LINE INDENT board = [ [ - 1 for i in range ( n ) ] for i in range ( n ) ] NEW_LINE move_x = [ 2 , 1 , - 1 , - 2 , - 2 , - 1 , 1 , 2 ] NEW_LINE move_y = [ 1 , 2 , 2 , 1 , - 1 , - 2 , - 2 , - 1 ] NEW_LINE board [ 0 ] [ 0 ] = 0 NEW_LINE pos = 1 NEW_LINE if ( not solveKTUtil ( n , board , 0 , 0 , move_x , move_y , pos ) ) : NEW_LINE INDENT print ( " Solution β does β not β exist " ) NEW_LINE DEDENT else : NEW_LINE INDENT printSolution ( n , board ) NEW_LINE DEDENT DEDENT def solveKTUtil ( n , board , curr_x , curr_y , move_x , move_y , pos ) : NEW_LINE INDENT if ( pos == n ** 2 ) : NEW_LINE INDENT return True NEW_LINE DEDENT for i in range ( 8 ) : NEW_LINE INDENT new_x = curr_x + move_x [ i ] NEW_LINE new_y = curr_y + move_y [ i ] NEW_LINE if ( isSafe ( new_x , new_y , board ) ) : NEW_LINE INDENT board [ new_x ] [ new_y ] = pos NEW_LINE if ( solveKTUtil ( n , board , new_x , new_y , move_x , move_y , pos + 1 ) ) : NEW_LINE INDENT return True NEW_LINE DEDENT board [ new_x ] [ new_y ] = - 1 NEW_LINE DEDENT DEDENT return False NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT solveKT ( n ) NEW_LINE DEDENT |
Rat in a Maze | Backtracking | Maze size ; A utility function to print solution matrix sol ; A utility function to check if x , y is valid index for N * N Maze ; if ( x , y outside maze ) return false ; This function solves the Maze problem using Backtracking . It mainly uses solveMazeUtil ( ) to solve the problem . It returns false if no path is possible , otherwise return true and prints the path in the form of 1 s . Please note that there may be more than one solutions , this function prints one of the feasable solutions . ; A recursive utility function to solve Maze problem ; if ( x , y is goal ) return True ; Check if maze [ x ] [ y ] is valid ; Check if the current block is already part of solution path . ; mark x , y as part of solution path ; Move forward in x direction ; If moving in x direction doesn 't give solution then Move down in y direction ; If moving in y direction doesn 't give solution then Move back in x direction ; If moving in backwards in x direction doesn 't give solution then Move upwards in y direction ; If none of the above movements work then BACKTRACK : unmark x , y as part of solution path ; Driver program to test above function | N = 4 NEW_LINE def printSolution ( sol ) : NEW_LINE INDENT for i in sol : NEW_LINE INDENT for j in i : NEW_LINE INDENT print ( str ( j ) + " β " , end = " " ) NEW_LINE DEDENT print ( " " ) NEW_LINE DEDENT DEDENT def isSafe ( maze , x , y ) : NEW_LINE INDENT if x >= 0 and x < N and y >= 0 and y < N and maze [ x ] [ y ] == 1 : NEW_LINE INDENT return True NEW_LINE DEDENT return False NEW_LINE DEDENT def solveMaze ( maze ) : NEW_LINE INDENT sol = [ [ 0 for j in range ( 4 ) ] for i in range ( 4 ) ] NEW_LINE if solveMazeUtil ( maze , 0 , 0 , sol ) == False : NEW_LINE INDENT print ( " Solution β doesn ' t β exist " ) ; NEW_LINE return False NEW_LINE DEDENT printSolution ( sol ) NEW_LINE return True NEW_LINE DEDENT def solveMazeUtil ( maze , x , y , sol ) : NEW_LINE INDENT if x == N - 1 and y == N - 1 and maze [ x ] [ y ] == 1 : NEW_LINE INDENT sol [ x ] [ y ] = 1 NEW_LINE return True NEW_LINE DEDENT if isSafe ( maze , x , y ) == True : NEW_LINE INDENT if sol [ x ] [ y ] == 1 : NEW_LINE INDENT return False NEW_LINE DEDENT sol [ x ] [ y ] = 1 NEW_LINE if solveMazeUtil ( maze , x + 1 , y , sol ) == True : NEW_LINE INDENT return True NEW_LINE DEDENT if solveMazeUtil ( maze , x , y + 1 , sol ) == True : NEW_LINE INDENT return True NEW_LINE DEDENT if solveMazeUtil ( maze , x - 1 , y , sol ) == True : NEW_LINE INDENT return True NEW_LINE DEDENT if solveMazeUtil ( maze , x , y - 1 , sol ) == True : NEW_LINE INDENT return True NEW_LINE DEDENT sol [ x ] [ y ] = 0 NEW_LINE return False NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT maze = [ [ 1 , 0 , 0 , 0 ] , [ 1 , 1 , 0 , 1 ] , [ 0 , 1 , 0 , 0 ] , [ 1 , 1 , 1 , 1 ] ] NEW_LINE solveMaze ( maze ) NEW_LINE DEDENT |
m Coloring Problem | Backtracking | A utility function to prsolution ; check if the colored graph is safe or not ; check for every edge ; This function solves the m Coloring problem using recursion . It returns false if the m colours cannot be assigned , otherwise , return true and prints assignments of colours to all vertices . Please note that there may be more than one solutions , this function prints one of the feasible solutions . ; if current index reached end ; if coloring is safe ; Prthe solution ; Assign each color from 1 to m ; Recur of the rest vertices ; Driver code ; Create following graph and test whether it is 3 colorable ( 3 ) -- - ( 2 ) | / | | / | | / | ( 0 ) -- - ( 1 ) ; Number of colors ; Initialize all color values as 0. This initialization is needed correct functioning of isSafe ( ) | def printSolution ( color ) : NEW_LINE INDENT print ( " Solution β Exists : " " β Following β are β the β assigned β colors β " ) NEW_LINE for i in range ( 4 ) : NEW_LINE INDENT print ( color [ i ] , end = " β " ) NEW_LINE DEDENT DEDENT def isSafe ( graph , color ) : NEW_LINE INDENT for i in range ( 4 ) : NEW_LINE INDENT for j in range ( i + 1 , 4 ) : NEW_LINE INDENT if ( graph [ i ] [ j ] and color [ j ] == color [ i ] ) : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT DEDENT return True NEW_LINE DEDENT def graphColoring ( graph , m , i , color ) : NEW_LINE INDENT if ( i == 4 ) : NEW_LINE INDENT if ( isSafe ( graph , color ) ) : NEW_LINE INDENT printSolution ( color ) NEW_LINE return True NEW_LINE DEDENT return False NEW_LINE DEDENT for j in range ( 1 , m + 1 ) : NEW_LINE INDENT color [ i ] = j NEW_LINE if ( graphColoring ( graph , m , i + 1 , color ) ) : NEW_LINE INDENT return True NEW_LINE DEDENT color [ i ] = 0 NEW_LINE DEDENT return False NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT graph = [ [ 0 , 1 , 1 , 1 ] , [ 1 , 0 , 1 , 0 ] , [ 1 , 1 , 0 , 1 ] , [ 1 , 0 , 1 , 0 ] , ] NEW_LINE m = 3 NEW_LINE color = [ 0 for i in range ( 4 ) ] NEW_LINE if ( not graphColoring ( graph , m , 0 , color ) ) : NEW_LINE INDENT print ( " Solution β does β not β exist " ) NEW_LINE DEDENT DEDENT |
m Coloring Problem | Backtracking | Python3 program for the above approach ; A node class which stores the color and the edges connected to the node ; Create a visited array of n nodes , initialized to zero ; maxColors used till now are 1 as all nodes are painted color 1 ; Do a full BFS traversal from all unvisited starting points ; If the starting point is unvisited , mark it visited and push it in queue ; BFS Travel starts here ; Checking all adjacent nodes to " top " edge in our queue ; IMPORTANT : If the color of the adjacent node is same , increase it by 1 ; If number of colors used shoots m , return 0 ; If the adjacent node is not visited , mark it visited and push it in queue ; Driver code ; Number of colors ; Create a vector of n + 1 nodes of type " node " The zeroth position is just dummy ( 1 to n to be used ) ; Add edges to each node as per given input ; Connect the undirected graph ; Display final answer | from queue import Queue NEW_LINE class node : NEW_LINE INDENT color = 1 NEW_LINE edges = set ( ) NEW_LINE DEDENT def canPaint ( nodes , n , m ) : NEW_LINE INDENT visited = [ 0 for _ in range ( n + 1 ) ] NEW_LINE maxColors = 1 NEW_LINE for _ in range ( 1 , n + 1 ) : NEW_LINE INDENT if visited [ _ ] : NEW_LINE INDENT continue NEW_LINE DEDENT visited [ _ ] = 1 NEW_LINE q = Queue ( ) NEW_LINE q . put ( _ ) NEW_LINE while not q . empty ( ) : NEW_LINE INDENT top = q . get ( ) NEW_LINE for _ in nodes [ top ] . edges : NEW_LINE INDENT if nodes [ top ] . color == nodes [ _ ] . color : NEW_LINE INDENT nodes [ _ ] . color += 1 NEW_LINE DEDENT maxColors = max ( maxColors , max ( nodes [ top ] . color , nodes [ _ ] . color ) ) NEW_LINE if maxColors > m : NEW_LINE INDENT print ( maxColors ) NEW_LINE return 0 NEW_LINE DEDENT if not visited [ _ ] : NEW_LINE INDENT visited [ _ ] = 1 NEW_LINE q . put ( _ ) NEW_LINE DEDENT DEDENT DEDENT DEDENT return 1 NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT n = 4 NEW_LINE graph = [ [ 0 , 1 , 1 , 1 ] , [ 1 , 0 , 1 , 0 ] , [ 1 , 1 , 0 , 1 ] , [ 1 , 0 , 1 , 0 ] ] NEW_LINE m = 3 NEW_LINE nodes = [ ] NEW_LINE for _ in range ( n + 1 ) : NEW_LINE INDENT nodes . append ( node ( ) ) NEW_LINE DEDENT for _ in range ( n ) : NEW_LINE INDENT for __ in range ( n ) : NEW_LINE INDENT if graph [ _ ] [ __ ] : NEW_LINE INDENT nodes [ _ ] . edges . add ( _ ) NEW_LINE nodes [ __ ] . edges . add ( __ ) NEW_LINE DEDENT DEDENT DEDENT print ( canPaint ( nodes , n , m ) ) NEW_LINE DEDENT |
Maximize pair decrements required to reduce all array elements except one to 0 | Function to count maximum number of steps to make ( N - 1 ) array elements to 0 ; Stores maximum count of steps to make ( N - 1 ) elements equal to 0 ; Stores array elements ; Traverse the array ; Insert arr [ i ] into PQ ; Extract top 2 elements from the array while ( N - 1 ) array elements become 0 ; Stores top element of PQ ; Pop the top element of PQ . ; Stores top element of PQ ; Pop the top element of PQ . ; Update X ; Update Y ; If X is not equal to 0 ; Insert X into PQ ; if Y is not equal to 0 ; Insert Y into PQ ; Update cntOp ; Driver Code | def cntMaxOperationToMakeN_1_0 ( arr , N ) : NEW_LINE INDENT cntOp = 0 NEW_LINE PQ = [ ] NEW_LINE for i in range ( N ) : NEW_LINE INDENT PQ . append ( arr [ i ] ) NEW_LINE DEDENT PQ = sorted ( PQ ) NEW_LINE while ( len ( PQ ) > 1 ) : NEW_LINE INDENT X = PQ [ - 1 ] NEW_LINE del PQ [ - 1 ] NEW_LINE Y = PQ [ - 1 ] NEW_LINE del PQ [ - 1 ] NEW_LINE X -= 1 NEW_LINE Y -= 1 NEW_LINE if ( X != 0 ) : NEW_LINE INDENT PQ . append ( X ) NEW_LINE DEDENT if ( Y != 0 ) : NEW_LINE INDENT PQ . append ( Y ) NEW_LINE DEDENT cntOp += 1 NEW_LINE PQ = sorted ( PQ ) NEW_LINE DEDENT return cntOp NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 1 , 2 , 3 , 4 , 5 ] NEW_LINE N = len ( arr ) NEW_LINE print ( cntMaxOperationToMakeN_1_0 ( arr , N ) ) NEW_LINE DEDENT |
Flip all K | Function to flip all K - bits of an unsigned number N ; Stores ( 2 ^ K ) - 1 ; Update N ; Print the answer ; Driver Code | def flippingBits ( N , K ) : NEW_LINE INDENT X = ( 1 << ( K - 1 ) ) - 1 NEW_LINE N = X - N NEW_LINE print ( N ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N , K = 1 , 8 NEW_LINE flippingBits ( N , K ) NEW_LINE DEDENT |
Generate a matrix having even sum of all diagonals in each 2 x 2 submatrices | Function to construct a matrix such that the sum elements in both diagonals of every 2 * 2 matrices is even ; Stores odd numbers ; Stores even numbers ; Store matrix elements such that sum of elements in both diagonals of every 2 * 2 submatrices is even ; Fill all the values of matrix elements ; Update odd ; Update even ; Prthe matrix ; Driver Code | def generateMatrix ( N ) : NEW_LINE INDENT odd = 1 ; NEW_LINE even = 2 ; NEW_LINE mat = [ [ 0 for i in range ( N + 1 ) ] for j in range ( N + 1 ) ] ; NEW_LINE for i in range ( 1 , N + 1 ) : NEW_LINE INDENT for j in range ( 1 , N + 1 ) : NEW_LINE INDENT if ( ( i + j ) % 2 == 0 ) : NEW_LINE INDENT mat [ i ] [ j ] = odd ; NEW_LINE odd += 2 ; NEW_LINE DEDENT else : NEW_LINE INDENT mat [ i ] [ j ] = even ; NEW_LINE even += 2 ; NEW_LINE DEDENT DEDENT DEDENT for i in range ( 1 , N + 1 ) : NEW_LINE INDENT for j in range ( 1 , N + 1 ) : NEW_LINE INDENT print ( mat [ i ] [ j ] , end = " β " ) ; NEW_LINE DEDENT print ( ) ; NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 4 ; NEW_LINE generateMatrix ( N ) ; NEW_LINE DEDENT |
Queries to calculate sum by alternating signs of array elements in a given range | Function to build the segment tree ; If current node is a leaf node of the segment tree ; Update tree [ index ] ; Update tree [ index ] ; Divide the segment tree ; Update on L segment tree ; Update on R segment tree ; Find the sum from L subtree and R subtree ; Function to update elements at index pos by val in the segment tree ; If current node is a leaf node ; If current index is even ; Update tree [ index ] ; Update tree [ index ] ; Divide the segment tree elements into L and R subtree ; If element lies in L subtree ; Update tree [ index ] ; Function to find the sum of array elements in the range [ L , R ] ; If start and end not lies in the range [ L , R ] ; If start and end comleately lies in the range [ L , R ] ; Stores sum from left subtree ; Stores sum from right subtree ; Driver code | def build ( tree , arr , start , end , index ) : NEW_LINE INDENT if ( start == end ) : NEW_LINE INDENT if ( start % 2 == 0 ) : NEW_LINE INDENT tree [ index ] = arr [ start ] NEW_LINE DEDENT else : NEW_LINE INDENT tree [ index ] = - arr [ start ] NEW_LINE DEDENT return NEW_LINE DEDENT mid = start + ( end - start ) // 2 NEW_LINE build ( tree , arr , start , mid , 2 * index + 1 ) NEW_LINE build ( tree , arr , mid + 1 , end , 2 * index + 2 ) NEW_LINE tree [ index ] = tree [ 2 * index + 1 ] + tree [ 2 * index + 2 ] NEW_LINE DEDENT def update ( tree , index , start , end , pos , val ) : NEW_LINE INDENT if ( start == end ) : NEW_LINE INDENT if ( start % 2 == 0 ) : NEW_LINE INDENT tree [ index ] = val NEW_LINE DEDENT else : NEW_LINE INDENT tree [ index ] = - val NEW_LINE DEDENT return NEW_LINE DEDENT mid = start + ( end - start ) // 2 NEW_LINE if ( mid >= pos ) : NEW_LINE INDENT update ( tree , 2 * index + 1 , start , mid , pos , val ) NEW_LINE DEDENT else : NEW_LINE INDENT update ( tree , 2 * index + 2 , mid + 1 , end , pos , val ) NEW_LINE DEDENT tree [ index ] = tree [ 2 * index + 1 ] + tree [ 2 * index + 2 ] NEW_LINE DEDENT def FindSum ( tree , start , end , L , R , index ) : NEW_LINE INDENT if ( L > end or R < start ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT if ( L <= start and R >= end ) : NEW_LINE INDENT return tree [ index ] NEW_LINE DEDENT mid = start + ( end - start ) // 2 NEW_LINE X = FindSum ( tree , start , mid , L , R , 2 * index + 1 ) NEW_LINE Y = FindSum ( tree , mid + 1 , end , L , R , 2 * index + 2 ) NEW_LINE return X + Y NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 1 , 2 , 3 , 4 ] NEW_LINE N = len ( arr ) NEW_LINE tree = [ 0 for i in range ( 4 * N + 5 ) ] NEW_LINE build ( tree , arr , 0 , N - 1 , 0 ) NEW_LINE Q = [ [ 2 , 0 , 3 ] , [ 1 , 1 , 5 ] , [ 2 , 1 , 2 ] ] NEW_LINE cntQuey = 3 NEW_LINE for i in range ( cntQuey ) : NEW_LINE INDENT if ( Q [ i ] [ 0 ] == 1 ) : NEW_LINE INDENT update ( tree , 0 , 0 , N - 1 , Q [ i ] [ 1 ] , Q [ i ] [ 2 ] ) NEW_LINE DEDENT else : NEW_LINE INDENT if ( Q [ i ] [ 1 ] % 2 == 0 ) : NEW_LINE INDENT print ( FindSum ( tree , 0 , N - 1 , Q [ i ] [ 1 ] , Q [ i ] [ 2 ] , 0 ) , end = " β " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( - FindSum ( tree , 0 , N - 1 , Q [ i ] [ 1 ] , Q [ i ] [ 2 ] , 0 ) , end = " β " ) NEW_LINE DEDENT DEDENT DEDENT DEDENT |
Split an array into minimum number of non | Function to split the array into minimum count of subarrays such that each subarray is either non - increasing or non - decreasing ; Initialize variable to keep track of current sequence ; Stores the required result ; Traverse the array , arr [ ] ; If current sequence is neither non - increasing nor non - decreasing ; If previous element is greater ; Update current ; If previous element is equal to the current element ; Update current ; Otherwise ; Update current ; If current sequence is in non - decreasing ; I f previous element is less than or equal to the current element ; Otherwise ; Update current as N and increment answer by 1 ; If current sequence is Non - Increasing ; If previous element is greater or equal to the current element ; Otherwise ; Update current as N and increment answer by 1 ; Print the answer ; Driver Code ; Given array ; Given size of array | def minimumSubarrays ( arr , n ) : NEW_LINE INDENT current = ' N ' NEW_LINE answer = 1 NEW_LINE for i in range ( 1 , n ) : NEW_LINE INDENT if ( current == ' N ' ) : NEW_LINE INDENT if ( arr [ i ] < arr [ i - 1 ] ) : NEW_LINE INDENT current = ' D ' NEW_LINE DEDENT elif ( arr [ i ] == arr [ i - 1 ] ) : NEW_LINE INDENT current = ' N ' NEW_LINE DEDENT else : NEW_LINE INDENT current = ' I ' NEW_LINE DEDENT DEDENT elif ( current == ' I ' ) : NEW_LINE INDENT if ( arr [ i ] >= arr [ i - 1 ] ) : NEW_LINE INDENT current = ' I ' NEW_LINE DEDENT else : NEW_LINE INDENT current = ' N ' NEW_LINE answer += 1 NEW_LINE DEDENT DEDENT else : NEW_LINE INDENT if ( arr [ i ] <= arr [ i - 1 ] ) : NEW_LINE INDENT current = ' D ' NEW_LINE DEDENT else : NEW_LINE INDENT current = ' N ' NEW_LINE answer += 1 NEW_LINE DEDENT DEDENT DEDENT print ( answer ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 2 , 3 , 9 , 5 , 4 , 6 , 8 ] NEW_LINE n = len ( arr ) NEW_LINE minimumSubarrays ( arr , n ) NEW_LINE DEDENT |
Convert a Matrix into another Matrix of given dimensions | Function to construct a matrix of size A * B from the given matrix elements ; Initialize a new matrix ; Traverse the matrix , mat [ ] [ ] ; Update idx ; Print the resultant matrix ; Driver Code | def ConstMatrix ( mat , N , M , A , B ) : NEW_LINE INDENT if ( N * M != A * B ) : NEW_LINE INDENT return - 1 NEW_LINE DEDENT idx = 0 ; NEW_LINE res = [ [ 0 for i in range ( B ) ] for i in range ( A ) ] NEW_LINE for i in range ( N ) : NEW_LINE INDENT for j in range ( M ) : NEW_LINE INDENT res [ idx // B ] [ idx % B ] = mat [ i ] [ j ] ; NEW_LINE idx += 1 NEW_LINE DEDENT DEDENT for i in range ( A ) : NEW_LINE INDENT for j in range ( B ) : NEW_LINE INDENT print ( res [ i ] [ j ] , end = " β " ) NEW_LINE DEDENT print ( ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT mat = [ [ 1 , 2 , 3 , 4 , 5 , 6 ] ] NEW_LINE A = 2 NEW_LINE B = 3 NEW_LINE N = len ( mat ) NEW_LINE M = len ( mat [ 0 ] ) NEW_LINE ConstMatrix ( mat , N , M , A , B ) NEW_LINE DEDENT |
Modify given array by reducing each element by its next smaller element | Function to print the final array after reducing each array element by its next smaller element ; Initialize stack ; To store the corresponding element ; If stack is not empty ; If top element is smaller than the current element ; Keep popping until stack is empty or top element is greater than the current element ; If stack is not empty ; Push current element ; Final array ; Driver Code ; Given array ; Function Call | def printFinalPrices ( arr ) : NEW_LINE INDENT minStk = [ ] NEW_LINE reduce = [ 0 ] * len ( arr ) NEW_LINE for i in range ( len ( arr ) - 1 , - 1 , - 1 ) : NEW_LINE INDENT if minStk : NEW_LINE INDENT if minStk [ - 1 ] <= arr [ i ] : NEW_LINE INDENT reduce [ i ] = minStk [ - 1 ] NEW_LINE DEDENT else : NEW_LINE INDENT while minStk and minStk [ - 1 ] > arr [ i ] : NEW_LINE INDENT minStk . pop ( ) NEW_LINE DEDENT if minStk : NEW_LINE INDENT reduce [ i ] = minStk [ - 1 ] NEW_LINE DEDENT DEDENT DEDENT minStk . append ( arr [ i ] ) NEW_LINE DEDENT for i in range ( len ( arr ) ) : NEW_LINE INDENT print ( arr [ i ] - reduce [ i ] , end = ' β ' ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 8 , 4 , 6 , 2 , 3 ] NEW_LINE printFinalPrices ( arr ) NEW_LINE DEDENT |
Generate array having differences between count of occurrences of every array element on its left and right | Function to construct array of differences of counts on the left and right of the given array ; Initialize left and right frequency arrays ; Construct left cumulative frequency table ; Construct right cumulative frequency table ; Print the result ; Driver Code ; Function Call | def constructArray ( A , N ) : NEW_LINE INDENT left = [ 0 ] * ( N + 1 ) NEW_LINE right = [ 0 ] * ( N + 1 ) NEW_LINE X = [ 0 ] * ( N + 1 ) NEW_LINE Y = [ 0 ] * ( N + 1 ) NEW_LINE for i in range ( 0 , N ) : NEW_LINE INDENT X [ i ] = left [ A [ i ] ] NEW_LINE left [ A [ i ] ] += 1 NEW_LINE DEDENT for i in range ( N - 1 , - 1 , - 1 ) : NEW_LINE INDENT Y [ i ] = right [ A [ i ] ] NEW_LINE right [ A [ i ] ] += 1 NEW_LINE DEDENT for i in range ( 0 , N ) : NEW_LINE INDENT print ( Y [ i ] - X [ i ] , end = " β " ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT A = [ 3 , 2 , 1 , 2 , 3 ] NEW_LINE N = len ( A ) NEW_LINE constructArray ( A , N ) NEW_LINE DEDENT |
Mean of distinct odd fibonacci nodes in a Linked List | Structure of a singly Linked List ; Stores data value of a Node ; Stores pointer to next Node ; Function to add a node at the beginning of the singly Linked List ; Create a new Node ; Insert the data into the Node ; Insert pointer to the next Node ; Update head_ref ; Function to find the largest element from the linked list ; Stores the largest element in the linked list ; Iterate over the linked list ; If max is less than head . data ; Update max ; Update head ; Function to store all Fibonacci numbers up to the largest element of the list ; Store all Fibonacci numbers up to Max ; Stores first element of Fibonacci number ; Stores second element of Fibonacci number ; Insert prev into hashmap ; Insert curr into hashmap ; Insert all elements of Fibonacci numbers up to Max ; Stores current fibonacci number ; Insert temp into hashmap ; Update prev ; Update curr ; Function to find the mean of odd Fibonacci nodes ; Stores the largest element in the linked list ; Stores all fibonacci numbers up to Max ; Stores current node of linked list ; Stores count of odd Fibonacci nodes ; Stores sum of all odd fibonacci nodes ; Traverse the linked list ; if the data value of current node is an odd number ; if data value of the node is present in hashmap ; Update cnt ; Update sum ; Remove current fibonacci number from hashmap so that duplicate elements can 't be counted ; Update curr ; Return the required mean ; Driver Code ; Stores head node of the linked list ; Insert all data values in the linked list | class Node : NEW_LINE INDENT def __init__ ( self ) : NEW_LINE INDENT self . data = 0 NEW_LINE self . next = None NEW_LINE DEDENT DEDENT def push ( head_ref , new_data ) : NEW_LINE INDENT new_node = Node ( ) NEW_LINE new_node . data = new_data ; NEW_LINE new_node . next = head_ref NEW_LINE head_ref = new_node ; NEW_LINE return head_ref NEW_LINE DEDENT def largestElement ( head_ref ) : NEW_LINE INDENT Max = - 10000000 NEW_LINE head = head_ref ; NEW_LINE while ( head != None ) : NEW_LINE INDENT if ( Max < head . data ) : NEW_LINE INDENT Max = head . data ; NEW_LINE DEDENT head = head . next ; NEW_LINE DEDENT return Max ; NEW_LINE DEDENT def createHashMap ( Max ) : NEW_LINE INDENT hashmap = set ( ) NEW_LINE prev = 0 ; NEW_LINE curr = 1 ; NEW_LINE hashmap . add ( prev ) ; NEW_LINE hashmap . add ( curr ) ; NEW_LINE while ( curr <= Max ) : NEW_LINE INDENT temp = curr + prev ; NEW_LINE hashmap . add ( temp ) ; NEW_LINE prev = curr ; NEW_LINE curr = temp ; NEW_LINE DEDENT return hashmap ; NEW_LINE DEDENT def meanofnodes ( head ) : NEW_LINE INDENT Max = largestElement ( head ) ; NEW_LINE hashmap = createHashMap ( Max ) ; NEW_LINE curr = head ; NEW_LINE cnt = 0 ; NEW_LINE sum = 0.0 ; NEW_LINE while ( curr != None ) : NEW_LINE INDENT if ( ( curr . data ) % 2 == 1 ) : NEW_LINE INDENT if ( curr . data in hashmap ) : NEW_LINE INDENT cnt += 1 NEW_LINE sum += curr . data ; NEW_LINE hashmap . remove ( curr . data ) ; NEW_LINE DEDENT DEDENT curr = curr . next ; NEW_LINE DEDENT return ( sum / cnt ) ; NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT head = None ; NEW_LINE head = push ( head , 5 ) ; NEW_LINE head = push ( head , 21 ) ; NEW_LINE head = push ( head , 8 ) ; NEW_LINE head = push ( head , 12 ) ; NEW_LINE head = push ( head , 3 ) ; NEW_LINE head = push ( head , 13 ) ; NEW_LINE head = push ( head , 144 ) ; NEW_LINE head = push ( head , 6 ) ; NEW_LINE print ( meanofnodes ( head ) ) NEW_LINE DEDENT |
Generate an alternate odd | Function to prthe required sequence ; Print ith odd number ; Driver Code | def findNumbers ( n ) : NEW_LINE INDENT i = 0 NEW_LINE while ( i <= n ) : NEW_LINE INDENT print ( 2 * i * i + 4 * i + 1 + i % 2 , end = " β " ) NEW_LINE i += 1 NEW_LINE DEDENT DEDENT n = 6 NEW_LINE findNumbers ( n ) NEW_LINE |
Program to calculate gross salary of a person | Function to calculate the salary of the person ; Condition to compute the allowance for the person ; Calculate gross salary ; Driver code ; Function call | def computeSalary ( basic , grade ) : NEW_LINE INDENT hra = 0.2 * basic NEW_LINE da = 0.5 * basic NEW_LINE pf = 0.11 * basic NEW_LINE if grade == ' A ' : NEW_LINE INDENT allowance = 1700.0 NEW_LINE DEDENT elif grade == ' B ' : NEW_LINE INDENT allowance = 1500.0 NEW_LINE DEDENT else : NEW_LINE INDENT allowance = 1300.0 ; NEW_LINE DEDENT gross = round ( basic + hra + da + allowance - pf ) NEW_LINE return gross NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT basic = 10000 NEW_LINE grade = ' A ' NEW_LINE print ( computeSalary ( basic , grade ) ) ; NEW_LINE DEDENT |
Rearrange and update array elements as specified by the given queries | Python3 program to implement the above approach ; Function to perform the given operations ; Dequeue to store the array elements ; Insert all element of the array into the dequeue ; Stores the size of the queue ; Traverse each query ; Query for left shift . ; Extract the element at the front of the queue ; Pop the element at the front of the queue ; Push the element at the back of the queue ; Query for right shift ; Extract the element at the back of the queue ; Pop the element at the back of the queue ; Push the element at the front of the queue ; Query for update ; Query to get the value ; Driver Code ; All possible Queries | from collections import deque NEW_LINE def Queries ( arr , N , Q ) : NEW_LINE INDENT dq = deque ( ) NEW_LINE for i in range ( N ) : NEW_LINE INDENT dq . append ( arr [ i ] ) NEW_LINE DEDENT sz = len ( Q ) NEW_LINE for i in range ( sz ) : NEW_LINE INDENT if ( Q [ i ] [ 0 ] == 0 ) : NEW_LINE INDENT front = dq [ 0 ] NEW_LINE dq . popleft ( ) NEW_LINE dq . appendleft ( front ) NEW_LINE DEDENT elif ( Q [ i ] [ 0 ] == 1 ) : NEW_LINE INDENT back = dq [ N - 1 ] NEW_LINE dq . popleft ( ) NEW_LINE dq . appendleft ( back ) NEW_LINE DEDENT elif ( Q [ i ] [ 0 ] == 2 ) : NEW_LINE INDENT dq [ Q [ i ] [ 1 ] ] = Q [ i ] [ 2 ] NEW_LINE DEDENT else : NEW_LINE INDENT print ( dq [ Q [ i ] [ 1 ] ] , end = " β " ) NEW_LINE DEDENT DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 1 , 2 , 3 , 4 , 5 ] NEW_LINE N = len ( arr ) NEW_LINE Q = [ [ 0 ] , [ 1 ] , [ 3 , 1 ] , [ 2 , 2 , 54 ] , [ 3 , 2 ] ] NEW_LINE Queries ( arr , N , Q ) NEW_LINE DEDENT |
Size of smallest subarray to be removed to make count of array elements greater and smaller than K equal | Python3 program to implement the above approach ; Function ot find the length of the smallest subarray ; Stores ( prefix Sum , index ) as ( key , value ) mappings ; Iterate till N ; Update the prefixSum ; Update the length ; Put the latest index to find the minimum length ; Update the length ; Return the answer ; Function to find the length of the largest subarray ; Stores the sum of all array elements after modification ; Change greater than k to 1 ; Change smaller than k to - 1 ; Change equal to k to 0 ; Update total_sum ; No deletion required , return 0 ; Delete smallest subarray that has sum = total_sum ; Driver Code ; Function call | import sys NEW_LINE def smallSubarray ( arr , n , total_sum ) : NEW_LINE INDENT m = { } NEW_LINE length = sys . maxsize NEW_LINE prefixSum = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT prefixSum += arr [ i ] NEW_LINE if ( prefixSum == total_sum ) : NEW_LINE INDENT length = min ( length , i + 1 ) NEW_LINE DEDENT m [ prefixSum ] = i NEW_LINE if ( ( prefixSum - total_sum ) in m . keys ( ) ) : NEW_LINE INDENT length = min ( length , i - m [ prefixSum - total_sum ] ) NEW_LINE DEDENT DEDENT return length NEW_LINE DEDENT def smallestSubarrayremoved ( arr , n , k ) : NEW_LINE INDENT total_sum = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( arr [ i ] > k ) : NEW_LINE INDENT arr [ i ] = 1 NEW_LINE DEDENT elif ( arr [ i ] < k ) : NEW_LINE INDENT arr [ i ] = - 1 NEW_LINE DEDENT else : NEW_LINE INDENT arr [ i ] = 0 NEW_LINE DEDENT total_sum += arr [ i ] NEW_LINE DEDENT if ( total_sum == 0 ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT else : NEW_LINE INDENT return smallSubarray ( arr , n , total_sum ) NEW_LINE DEDENT DEDENT arr = [ 12 , 16 , 12 , 13 , 10 ] NEW_LINE K = 13 NEW_LINE n = len ( arr ) NEW_LINE print ( smallestSubarrayremoved ( arr , n , K ) ) NEW_LINE |
Balanced Ternary Number System | Python3 program to convert positive decimals into balanced ternary system ; Driver Code | def balancedTernary ( n ) : NEW_LINE INDENT output = " " NEW_LINE while ( n > 0 ) : NEW_LINE INDENT rem = n % 3 NEW_LINE n = n // 3 NEW_LINE if ( rem == 2 ) : NEW_LINE INDENT rem = - 1 NEW_LINE n += 1 NEW_LINE DEDENT if ( rem == 0 ) : NEW_LINE INDENT output = '0' + output NEW_LINE DEDENT else : NEW_LINE INDENT if ( rem == 1 ) : NEW_LINE INDENT output = '1' + output NEW_LINE DEDENT else : NEW_LINE INDENT output = ' Z ' + output NEW_LINE DEDENT DEDENT DEDENT return output NEW_LINE DEDENT n = 238 NEW_LINE print ( " Equivalent β Balanced β Ternary β of " , n , " is : " , balancedTernary ( n ) ) NEW_LINE |
Spt function or Smallest Parts Function of a given number | Python3 implementation to find the Spt Function to given number ; Variable to store spt function of a number ; Function to add value of frequency of minimum element among all representations of n ; Find the value of frequency of minimum element ; Calculate spt ; Recursive function to find different ways in which n can be written as a sum of at one or more positive integers ; If sum becomes n , consider this representation ; Start from previous element in the representation till n ; Include current element from representation ; Call function again with reduced sum ; Backtrack - remove current element from representation ; Function to find the spt function ; Using recurrence find different ways in which n can be written as a sum of at 1 or more positive integers ; Driver Code | import sys NEW_LINE spt = 0 NEW_LINE def printVector ( arr ) : NEW_LINE INDENT global spt NEW_LINE min_i = sys . maxsize NEW_LINE for i in range ( len ( arr ) ) : NEW_LINE INDENT min_i = min ( min_i , arr [ i ] ) NEW_LINE DEDENT freq = arr . count ( min_i ) NEW_LINE spt += freq NEW_LINE DEDENT def findWays ( arr , i , n ) : NEW_LINE INDENT if ( n == 0 ) : NEW_LINE INDENT printVector ( arr ) NEW_LINE DEDENT for j in range ( i , n + 1 ) : NEW_LINE INDENT arr . append ( j ) NEW_LINE findWays ( arr , j , n - j ) NEW_LINE del arr [ - 1 ] NEW_LINE DEDENT DEDENT def spt_function ( n ) : NEW_LINE INDENT arr = [ ] NEW_LINE findWays ( arr , 1 , n ) NEW_LINE print ( spt ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 4 NEW_LINE spt_function ( N ) NEW_LINE DEDENT |
Find initial integral solution of Linear Diophantine equation if finite solution exists | Python3 program for the above approach ; Function to implement the extended euclid algorithm ; Base Case ; Recursively find the gcd ; Function to prlet the solutions of the given equations ax + by = c ; Condition for infinite solutions ; Condition for no solutions exist ; Condition for no solutions exist ; Print the solution ; Given coefficients ; Function Call | import math NEW_LINE x , y = 0 , 0 NEW_LINE def gcd_extend ( a , b ) : NEW_LINE INDENT global x , y NEW_LINE if ( b == 0 ) : NEW_LINE INDENT x = 1 NEW_LINE y = 0 NEW_LINE return a NEW_LINE DEDENT else : NEW_LINE INDENT g = gcd_extend ( b , a % b ) NEW_LINE x1 , y1 = x , y NEW_LINE x = y1 NEW_LINE y = x1 - math . floor ( a / b ) * y1 NEW_LINE return g NEW_LINE DEDENT DEDENT def print_solution ( a , b , c ) : NEW_LINE INDENT if ( a == 0 and b == 0 ) : NEW_LINE INDENT if ( c == 0 ) : NEW_LINE INDENT print ( " Infinite β Solutions β Exist " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No β Solution β exists " ) NEW_LINE DEDENT DEDENT gcd = gcd_extend ( a , b ) NEW_LINE if ( c % gcd != 0 ) : NEW_LINE INDENT print ( " No β Solution β exists " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " x β = β " , int ( x * ( c / gcd ) ) , " , β y β = β " , int ( y * ( c / gcd ) ) , sep = " " ) NEW_LINE DEDENT DEDENT a = 4 NEW_LINE b = 18 NEW_LINE c = 10 NEW_LINE print_solution ( a , b , c ) NEW_LINE |
Count of pairs whose bitwise AND is a power of 2 | Function to check if x is power of 2 ; Returns true if x is a power of 2 ; Function to return the number of valid pairs ; Iterate for all possible pairs ; Bitwise and value of the pair is passed ; Return the final count ; ; Given array ; Function Call | def check ( x ) : NEW_LINE INDENT return x and ( not ( x & ( x - 1 ) ) ) NEW_LINE DEDENT def count ( arr , n ) : NEW_LINE INDENT cnt = 0 NEW_LINE for i in range ( n - 1 ) : NEW_LINE INDENT for j in range ( i + 1 , n ) : NEW_LINE INDENT if check ( arr [ i ] & arr [ j ] ) : NEW_LINE INDENT cnt = cnt + 1 NEW_LINE DEDENT DEDENT DEDENT return cnt NEW_LINE DEDENT / * Driver Code * / NEW_LINE arr = [ 6 , 4 , 2 , 3 ] NEW_LINE n = len ( arr ) NEW_LINE print ( count ( arr , n ) ) NEW_LINE |
Check if the Matrix follows the given constraints or not | Python3 implementation of the above approach ; Function checks if n is prime or not ; Corner case ; Check from 2 to sqrt ( n ) ; Function returns sum of all elements of matrix ; Stores the sum of the matrix ; Function to check if all a [ i ] [ j ] with prime ( i + j ) are prime ; If index is prime ; If element not prime ; Driver code ; Check for both conditions | import math NEW_LINE def isPrime ( n ) : NEW_LINE INDENT if ( n <= 1 ) : 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 takeSum ( a , n , m ) : NEW_LINE INDENT sum = 0 NEW_LINE for i in range ( 0 , n ) : NEW_LINE INDENT for j in range ( 0 , m ) : NEW_LINE INDENT sum += a [ i ] [ j ] NEW_LINE DEDENT DEDENT return sum NEW_LINE DEDENT def checkIndex ( n , m , a ) : NEW_LINE INDENT for i in range ( 0 , n ) : NEW_LINE INDENT for j in range ( 0 , m ) : NEW_LINE INDENT if ( isPrime ( i + j ) ) : NEW_LINE INDENT if ( isPrime ( a [ i ] [ j ] ) != True ) : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT DEDENT DEDENT return True NEW_LINE DEDENT n = 4 NEW_LINE m = 5 NEW_LINE a = [ [ 1 , 2 , 3 , 2 , 2 ] , [ 2 , 2 , 7 , 7 , 7 ] , [ 7 , 7 , 21 , 7 , 10 ] , [ 2 , 2 , 3 , 6 , 7 ] ] NEW_LINE sum = takeSum ( a , n , m ) NEW_LINE if ( isPrime ( sum ) and checkIndex ( n , m , a ) ) : NEW_LINE INDENT print ( " YES " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " NO " ) NEW_LINE DEDENT |
Count of all possible pairs of array elements with same parity | Function to return the answer ; Generate all possible pairs ; Increment the count if both even or both odd ; Driver Code | def countPairs ( A , n ) : 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 if ( ( A [ i ] % 2 == 0 and A [ j ] % 2 == 0 ) or ( A [ i ] % 2 != 0 and A [ j ] % 2 != 0 ) ) : NEW_LINE INDENT count += 1 NEW_LINE DEDENT DEDENT DEDENT return count NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT A = [ 1 , 2 , 3 , 1 , 3 ] NEW_LINE n = len ( A ) NEW_LINE print ( countPairs ( A , n ) ) NEW_LINE DEDENT |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.