text
stringlengths 17
3.65k
| code
stringlengths 70
5.84k
|
---|---|
Split a string in equal parts such that all parts are palindromes | Function to return the frequency array for the given string ; Function to return the required count ; Add frequencies of the even appearing characters ; Count of the characters that appeared odd number of times ; If there are no characters with odd frequency ; If there are no characters with even frequency ; Only a single character with odd frequency ; More than 1 character with odd frequency string isn 't a palindrome ; All odd appearing characters can also contribute to the even length palindrome if one character is removed from the frequency leaving it as even ; If k palindromes are possible where k is the number of characters with odd frequency ; Current character can no longer be an element in a string other than the mid character ; If current character has odd frequency > 1 take two characters which can be used in any of the parts ; Update the frequency ; If not possible , then every character of the string will act as a separate palindrome ; Driver code | def getFrequencies ( string ) : NEW_LINE INDENT freq = [ 0 ] * 26 NEW_LINE for i in range ( len ( string ) ) : NEW_LINE INDENT freq [ ord ( string [ i ] ) - ord ( ' a ' ) ] += 1 NEW_LINE DEDENT return freq NEW_LINE DEDENT def countMinParts ( string ) : NEW_LINE INDENT n = len ( string ) NEW_LINE freq = getFrequencies ( string ) NEW_LINE oddFreq = [ ] NEW_LINE evenFreq = [ ] NEW_LINE sumEven = 0 NEW_LINE for i in range ( 26 ) : NEW_LINE INDENT if freq [ i ] == 0 : NEW_LINE INDENT continue NEW_LINE DEDENT if freq [ i ] % 2 == 0 : NEW_LINE INDENT evenFreq . append ( freq [ i ] ) NEW_LINE DEDENT else : NEW_LINE INDENT oddFreq . append ( freq [ i ] ) NEW_LINE DEDENT DEDENT for i in range ( len ( evenFreq ) ) : NEW_LINE INDENT sumEven += evenFreq [ i ] NEW_LINE DEDENT if len ( oddFreq ) == 0 : NEW_LINE INDENT return 1 NEW_LINE DEDENT if sumEven == 0 : NEW_LINE INDENT if len ( oddFreq ) == 1 : NEW_LINE INDENT return 1 NEW_LINE DEDENT return 0 NEW_LINE DEDENT i = 0 NEW_LINE while ( i < len ( oddFreq ) ) : NEW_LINE INDENT if ( ( sumEven / 2 ) % len ( oddFreq ) == 0 ) : NEW_LINE INDENT return len ( oddFreq ) NEW_LINE DEDENT if ( oddFreq [ i ] == 1 ) : NEW_LINE INDENT i += 1 NEW_LINE continue NEW_LINE DEDENT sumEven += 2 NEW_LINE oddFreq [ i ] = oddFreq [ i ] - 2 NEW_LINE DEDENT return n NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT s = " noonpeep " NEW_LINE print ( countMinParts ( s ) ) NEW_LINE DEDENT |
Substring Reverse Pattern | Function to print the required pattern ; Print the unmodified string ; Reverse the string ; Replace the first and last character by ' * ' then second and second last character and so on until the string has characters remaining ; Driver code | def printPattern ( s , n ) : NEW_LINE INDENT print ( ' ' . join ( s ) ) NEW_LINE i , j = 0 , n - 1 NEW_LINE while i < j : NEW_LINE INDENT s [ i ] , s [ j ] = s [ j ] , s [ i ] NEW_LINE i += 1 NEW_LINE j -= 1 NEW_LINE DEDENT i , j = 0 , n - 1 NEW_LINE while j - i > 1 : NEW_LINE INDENT s [ i ] , s [ j ] = ' * ' , ' * ' NEW_LINE print ( ' ' . join ( s ) ) NEW_LINE i += 1 NEW_LINE j -= 1 NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT s = " geeks " NEW_LINE n = len ( s ) NEW_LINE printPattern ( list ( s ) , n ) NEW_LINE DEDENT |
Check if the string satisfies the given condition | Function that returns true if n is prime ; Corner cases ; This is checked so that we can skip middle five numbers in below loop ; Function that returns true if c is a vowel ; Function that returns true if the count of vowels in word is prime ; If count of vowels is prime ; Driver code | def prime ( n ) : NEW_LINE INDENT if ( n <= 1 ) : NEW_LINE INDENT return False NEW_LINE DEDENT if ( n <= 3 ) : NEW_LINE INDENT return True NEW_LINE DEDENT if ( n % 2 == 0 or n % 3 == 0 ) : NEW_LINE INDENT return False NEW_LINE DEDENT i = 5 NEW_LINE while i * i <= n : NEW_LINE INDENT if ( n % i == 0 or n % ( i + 2 ) == 0 ) : NEW_LINE INDENT return False NEW_LINE DEDENT i += 6 NEW_LINE DEDENT return True NEW_LINE DEDENT def isVowel ( c ) : NEW_LINE INDENT c = c . lower ( ) NEW_LINE if ( c == ' a ' or c == ' e ' or c == ' i ' or c == ' o ' or c == ' u ' ) : NEW_LINE INDENT return True NEW_LINE DEDENT return False NEW_LINE DEDENT def isValidString ( word ) : NEW_LINE INDENT cnt = 0 ; NEW_LINE for i in range ( len ( word ) ) : NEW_LINE INDENT if ( isVowel ( word [ i ] ) ) : NEW_LINE INDENT cnt += 1 NEW_LINE DEDENT DEDENT if ( prime ( cnt ) ) : NEW_LINE INDENT return True NEW_LINE DEDENT else : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT s = " geeksforgeeks " NEW_LINE if ( isValidString ( s ) ) : NEW_LINE INDENT print ( " YES " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " NO " ) NEW_LINE DEDENT DEDENT |
Concatenate suffixes of a String | Function to print the expansion of the string ; Take sub - string from i to n - 1 ; Print the sub - string ; Driver code | def printExpansion ( str ) : NEW_LINE INDENT suff = " " NEW_LINE for i in range ( len ( str ) - 1 , - 1 , - 1 ) : NEW_LINE INDENT suff = suff + str [ i ] NEW_LINE print ( suff , end = " " ) NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT str = " geeks " NEW_LINE printExpansion ( str ) NEW_LINE DEDENT |
Solve the Logical Expression given by string | Python3 program to solve the logical expression . ; Function to evaluate the logical expression ; traversing string from the end . ; for NOT operation ; for AND and OR operation ; Driver code | import math as mt NEW_LINE def logicalExpressionEvaluation ( string ) : NEW_LINE INDENT arr = list ( ) NEW_LINE n = len ( string ) NEW_LINE for i in range ( n - 1 , - 1 , - 1 ) : NEW_LINE INDENT if ( string [ i ] == " [ " ) : NEW_LINE INDENT s = list ( ) NEW_LINE while ( arr [ - 1 ] != " ] " ) : NEW_LINE INDENT s . append ( arr [ - 1 ] ) NEW_LINE arr . pop ( ) NEW_LINE DEDENT arr . pop ( ) NEW_LINE if ( len ( s ) == 3 ) : NEW_LINE INDENT if s [ 2 ] == "1" : NEW_LINE INDENT arr . append ( "0" ) NEW_LINE DEDENT else : NEW_LINE INDENT arr . append ( "1" ) NEW_LINE DEDENT DEDENT elif ( len ( s ) == 5 ) : NEW_LINE INDENT a = int ( s [ 0 ] ) - 48 NEW_LINE b = int ( s [ 4 ] ) - 48 NEW_LINE c = 0 NEW_LINE if s [ 2 ] == " & " : NEW_LINE INDENT c = a & b NEW_LINE DEDENT else : NEW_LINE INDENT c = a | b NEW_LINE DEDENT arr . append ( ( c ) + 48 ) NEW_LINE DEDENT DEDENT else : NEW_LINE INDENT arr . append ( string [ i ] ) NEW_LINE DEDENT DEDENT return arr [ - 1 ] NEW_LINE DEDENT string = " [ | , [ & ,1 , [ ! , 0 ] ] , [ ! , [ | , [ β , 1,0 ] , [ ! ,1 ] ] ] ] " NEW_LINE print ( logicalExpressionEvaluation ( string ) ) NEW_LINE |
Find number of substrings of length k whose sum of ASCII value of characters is divisible by k | Python3 program to find number of substrings of length k whose sum of ASCII value of characters is divisible by k ; Finding length of string ; finding sum of ASCII value of first substring ; Using sliding window technique to find sum of ASCII value of rest of the substring ; checking if sum is divisible by k ; Driver code | def count ( s , k ) : NEW_LINE INDENT n = len ( s ) NEW_LINE d , count = 0 , 0 NEW_LINE for i in range ( k ) : NEW_LINE INDENT d += ord ( s [ i ] ) NEW_LINE if ( d % k == 0 ) : NEW_LINE INDENT count += 1 NEW_LINE for i in range ( k , n ) : NEW_LINE INDENT prev = ord ( s [ i - k ] ) NEW_LINE d -= prev NEW_LINE d += ord ( s [ i ] ) NEW_LINE if ( d % k == 0 ) : NEW_LINE INDENT count += 1 NEW_LINE return count NEW_LINE DEDENT DEDENT DEDENT DEDENT DEDENT s = " bcgabc " NEW_LINE k = 3 NEW_LINE ans = count ( s , k ) NEW_LINE print ( ans ) NEW_LINE |
String which when repeated exactly K times gives a permutation of S | Function to return a string which when repeated exactly k times gives a permutation of s ; size of string ; to frequency of each character ; get frequency of each character ; to store final answer ; check if frequency is divisible by k ; add to answer ; if frequency is not divisible by k ; Driver code ; function call | def K_String ( s , k ) : NEW_LINE INDENT n = len ( s ) NEW_LINE fre = [ 0 ] * 26 NEW_LINE for i in range ( n ) : NEW_LINE INDENT fre [ ord ( s [ i ] ) - ord ( ' a ' ) ] += 1 NEW_LINE DEDENT str = " " NEW_LINE for i in range ( 26 ) : NEW_LINE INDENT if ( fre [ i ] % k == 0 ) : NEW_LINE INDENT x = fre [ i ] // k NEW_LINE while ( x ) : NEW_LINE INDENT str += chr ( i + ord ( ' a ' ) ) NEW_LINE x -= 1 NEW_LINE DEDENT DEDENT else : NEW_LINE INDENT return " - 1" NEW_LINE DEDENT DEDENT return str NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT s = " aabb " NEW_LINE k = 2 NEW_LINE print ( K_String ( s , k ) ) NEW_LINE DEDENT |
Maximum even length sub | Python3 code to find the maximum length of sub - string ( of even length ) which can be arranged into a Palindrome ; function that returns true if the given sub - string can be arranged into a Palindrome ; This function returns the maximum length of the sub - string ( of even length ) which can be arranged into a Palindrome ; If we reach end of the string ; if string is of even length ; if string can be arranged into a palindrome ; Even length sub - string ; Check if current sub - string can be arranged into a palindrome ; Odd length sub - string ; Driver code | from collections import defaultdict NEW_LINE def canBePalindrome ( count ) : NEW_LINE INDENT for key in count : NEW_LINE INDENT if count [ key ] % 2 != 0 : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT return True NEW_LINE DEDENT def maxPal ( string , count , start , end ) : NEW_LINE INDENT if end == len ( string ) : NEW_LINE INDENT if ( end - start ) % 2 == 0 : NEW_LINE INDENT if canBePalindrome ( count ) == True : NEW_LINE INDENT return end - start NEW_LINE DEDENT DEDENT return 0 NEW_LINE DEDENT else : NEW_LINE INDENT if ( end - start ) % 2 == 0 : NEW_LINE INDENT if canBePalindrome ( count ) == True : NEW_LINE INDENT count [ string [ end ] ] += 1 NEW_LINE return max ( end - start , maxPal ( string , count , start , end + 1 ) ) NEW_LINE DEDENT else : NEW_LINE INDENT count [ string [ end ] ] += 1 NEW_LINE return maxPal ( string , count , start , end + 1 ) NEW_LINE DEDENT DEDENT else : NEW_LINE INDENT count [ string [ end ] ] += 1 NEW_LINE length = maxPal ( string , count . copy ( ) , start , end + 1 ) NEW_LINE count [ string [ end ] ] -= 1 NEW_LINE count [ string [ start ] ] -= 1 NEW_LINE return max ( length , maxPal ( string , count , start + 1 , end ) ) NEW_LINE DEDENT DEDENT DEDENT string = '124565463' NEW_LINE start , end = 0 , 0 NEW_LINE count = defaultdict ( lambda : 0 ) NEW_LINE print ( maxPal ( string , count , start , end ) ) NEW_LINE |
Minimum deletions from string to reduce it to string with at most 2 unique characters | Function to find the minimum deletions ; Array to store the occurrences of each characters ; Length of the string ; ASCII of the character ; Increasing the frequency for this character ; Choosing two character ; Finding the minimum deletion ; Driver code | def check ( s ) : NEW_LINE INDENT fr = [ 0 ] * 26 NEW_LINE n = len ( s ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT x = ord ( s [ i ] ) NEW_LINE fr [ x - 97 ] += 1 NEW_LINE DEDENT minimum = 99999999999 NEW_LINE for i in range ( 26 ) : NEW_LINE INDENT for j in range ( i + 1 , 26 ) : NEW_LINE INDENT z = fr [ i ] + fr [ j ] NEW_LINE minimum = min ( minimum , n - z ) NEW_LINE DEDENT DEDENT return minimum NEW_LINE DEDENT s = " geeksforgeeks " NEW_LINE print ( check ( s ) ) NEW_LINE |
Count and Print the alphabets having ASCII value not in the range [ l , r ] | Function to count the number of characters whose ascii value not in range [ l , r ] ; Initializing the count to 0 ; using map to pra character only once ; Increment the count if the value is less ; return the count ; Driver Code | def CountCharacters ( str , l , r ) : NEW_LINE INDENT cnt = 0 NEW_LINE m = { } NEW_LINE length = len ( str ) NEW_LINE for i in range ( 0 , length ) : NEW_LINE INDENT if ( not ( l <= ord ( str [ i ] ) and ord ( str [ i ] ) <= r ) ) : NEW_LINE INDENT cnt += 1 NEW_LINE if ord ( str [ i ] ) not in m : NEW_LINE INDENT m [ ord ( str [ i ] ) ] = 0 NEW_LINE print ( str [ i ] , end = " β " ) NEW_LINE DEDENT m [ ord ( str [ i ] ) ] += 1 NEW_LINE DEDENT DEDENT return cnt NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT str = " geeksforgeeks " NEW_LINE str = str . strip ( ) NEW_LINE l = 102 NEW_LINE r = 111 NEW_LINE print ( " Characters β with β ASCII β values " , end = " " ) NEW_LINE print ( " not in the range [ l , r ] " , β " in the given string are : " , β end β = β " " ) NEW_LINE print ( " and their count is " , CountCharacters ( str , l , r ) ) NEW_LINE DEDENT |
Final state of the string after modification | Function to return final positions of the boxes ; Populate forces going from left to right ; Populate forces going from right to left ; return final state of boxes ; Driver code ; Function call to print answer | def pushBoxes ( S ) : NEW_LINE INDENT N = len ( S ) NEW_LINE force = [ 0 ] * N NEW_LINE f = 0 NEW_LINE for i in range ( 0 , N ) : NEW_LINE INDENT if S [ i ] == ' R ' : NEW_LINE INDENT f = N NEW_LINE DEDENT elif S [ i ] == ' L ' : NEW_LINE INDENT f = 0 NEW_LINE DEDENT else : NEW_LINE INDENT f = max ( f - 1 , 0 ) NEW_LINE DEDENT force [ i ] += f NEW_LINE DEDENT f = 0 NEW_LINE for i in range ( N - 1 , - 1 , - 1 ) : NEW_LINE INDENT if S [ i ] == ' L ' : NEW_LINE INDENT f = N NEW_LINE DEDENT elif S [ i ] == ' R ' : NEW_LINE INDENT f = 0 NEW_LINE DEDENT else : NEW_LINE INDENT f = max ( f - 1 , 0 ) NEW_LINE DEDENT force [ i ] -= f NEW_LINE DEDENT return " " . join ( ' . ' if f == 0 else ' R ' if f > 0 else ' L ' for f in force ) NEW_LINE DEDENT S = " . L . R . . . LR . . L . . " NEW_LINE print ( pushBoxes ( S ) ) NEW_LINE |
Count the number of words having sum of ASCII values less than and greater than k | Function to count the words ; Sum of ascii values ; Number of words having sum of ascii less than k ; If character is a space ; Add the ascii value to sum ; Handling the Last word separately ; Driver code | def CountWords ( str , k ) : NEW_LINE INDENT sum = 0 NEW_LINE NumberOfWords = 0 NEW_LINE counter = 0 NEW_LINE l = len ( str ) NEW_LINE for i in range ( l ) : NEW_LINE INDENT if ( str [ i ] == ' β ' ) : NEW_LINE INDENT if ( sum < k ) : NEW_LINE INDENT counter += 1 NEW_LINE DEDENT sum = 0 NEW_LINE NumberOfWords += 1 NEW_LINE DEDENT else : NEW_LINE INDENT sum += ord ( str [ i ] ) NEW_LINE DEDENT DEDENT NumberOfWords += 1 NEW_LINE if ( sum < k ) : NEW_LINE INDENT counter += 1 NEW_LINE DEDENT print ( " Number β of β words β having β sum β of β ASCII " , " values β less β than β k β = " , counter ) NEW_LINE print ( " Number β of β words β having β sum β of β ASCII β values " , " greater β than β or β equal β to β k β = " , NumberOfWords - counter ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT str = " Learn β how β to β code " NEW_LINE k = 400 NEW_LINE CountWords ( str , k ) NEW_LINE DEDENT |
Rearrange a string in the form of integer sum followed by the minimized character | function to return maximum volume ; separate digits and alphabets ; change digit sum to string ; change alphabet sum to string ; concatenate sum to alphabets string ; Driver code | def separateChar ( str__ ) : NEW_LINE INDENT n = len ( str__ ) NEW_LINE digitSum = 0 NEW_LINE alphabetSum = 0 NEW_LINE j = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( ord ( str__ [ i ] ) >= 48 and ord ( str__ [ i ] ) <= 56 ) : NEW_LINE INDENT digitSum += ord ( str__ [ i ] ) - ord ( '0' ) NEW_LINE DEDENT else : NEW_LINE INDENT alphabetSum += ord ( str__ [ i ] ) - ord ( ' a ' ) + 1 NEW_LINE alphabetSum %= 26 NEW_LINE DEDENT DEDENT sumStr = str ( digitSum ) NEW_LINE alphabetStr = chr ( alphabetSum + ord ( ' a ' ) - 1 ) NEW_LINE sumStr += alphabetStr NEW_LINE return sumStr NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT str__ = "3652adyz3423" NEW_LINE print ( separateChar ( str__ ) ) NEW_LINE DEDENT |
Find the count of palindromic sub | Python3 program to find the count of palindromic sub - string of a string in it 's ascending form ; function to return count of palindromic sub - string ; calculate frequency ; calculate count of palindromic sub - string ; return result ; Driver Code | MAX_CHAR = 26 NEW_LINE def countPalindrome ( str ) : NEW_LINE INDENT n = len ( str ) NEW_LINE sum = 0 NEW_LINE hashTable = [ 0 ] * MAX_CHAR NEW_LINE for i in range ( n ) : NEW_LINE INDENT hashTable [ ord ( str [ i ] ) - ord ( ' a ' ) ] += 1 NEW_LINE DEDENT for i in range ( 26 ) : NEW_LINE INDENT if ( hashTable [ i ] ) : NEW_LINE INDENT sum += ( hashTable [ i ] * ( hashTable [ i ] + 1 ) // 2 ) NEW_LINE DEDENT DEDENT return sum NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT str = " ananananddd " NEW_LINE print ( countPalindrome ( str ) ) NEW_LINE DEDENT |
Minimum number of elements to be removed so that pairwise consecutive elements are same | Function to count the minimum number of elements to remove from a number so that pairwise two consecutive digits are same . ; initialize counting variable ; check if two consecutive digits are same ; Driver code | def countConsecutive ( s ) : NEW_LINE INDENT count = - 1 NEW_LINE for i in range ( len ( s ) - 1 ) : NEW_LINE INDENT if ( i <= len ( s ) ) : NEW_LINE INDENT if ( s [ i ] is s [ i + 1 ] ) : NEW_LINE INDENT i += 1 NEW_LINE DEDENT else : NEW_LINE INDENT count += 1 NEW_LINE DEDENT DEDENT DEDENT return count NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT str = "44522255" NEW_LINE print ( countConsecutive ( str ) ) NEW_LINE DEDENT |
Smallest odd digits number not less than N | function to check if all digits are odd of a given number ; iterate for all digits ; if digit is even ; all digits are odd ; function to return the smallest number with all digits odd ; iterate till we find a number with all digits odd ; Driver Code | def check_digits ( n ) : NEW_LINE INDENT while ( n ) : NEW_LINE INDENT if ( ( n % 10 ) % 2 == 0 ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT n = int ( n / 10 ) NEW_LINE DEDENT return 1 NEW_LINE DEDENT def smallest_number ( n ) : NEW_LINE INDENT i = n NEW_LINE while ( 1 ) : NEW_LINE INDENT if ( check_digits ( i ) ) : NEW_LINE INDENT return i NEW_LINE DEDENT i += 1 NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 2397 NEW_LINE print ( smallest_number ( N ) ) NEW_LINE DEDENT |
Smallest odd digits number not less than N | function to return the smallest number with all digits odd ; convert the number to string to perform operations ; find out the first even number ; if no even numbers are there , than n is the answer ; add all digits till first even ; increase the even digit by 1 ; add 1 to the right of the even number ; Driver Code | def smallestNumber ( n ) : NEW_LINE INDENT num = 0 NEW_LINE s = " " NEW_LINE duplicate = n NEW_LINE while ( n ) : NEW_LINE INDENT s = chr ( n % 10 + 48 ) + s NEW_LINE n //= 10 NEW_LINE DEDENT index = - 1 NEW_LINE for i in range ( len ( s ) ) : NEW_LINE INDENT digit = ord ( s [ i ] ) - ord ( '0' ) NEW_LINE if ( ( digit & 1 ) == 0 ) : NEW_LINE INDENT index = i NEW_LINE break NEW_LINE DEDENT DEDENT if ( index == - 1 ) : NEW_LINE INDENT return duplicate NEW_LINE DEDENT for i in range ( index ) : NEW_LINE INDENT num = num * 10 + ( ord ( s [ i ] ) - ord ( '0' ) ) NEW_LINE DEDENT num = num * 10 + ( ord ( s [ index ] ) - ord ( '0' ) + 1 ) NEW_LINE for i in range ( index + 1 , len ( s ) ) : NEW_LINE INDENT num = num * 10 + 1 NEW_LINE DEDENT return num NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT N = 2397 NEW_LINE print ( smallestNumber ( N ) ) NEW_LINE DEDENT |
Count and Print the alphabets having ASCII value in the range [ l , r ] | Function to count the number of characters whose ascii value is in range [ l , r ] ; Initializing the count to 0 ; Increment the count if the value is less ; return the count ; Driver code | def CountCharacters ( str1 , l , r ) : NEW_LINE INDENT cnt = 0 ; NEW_LINE len1 = len ( str1 ) NEW_LINE for i in str1 : NEW_LINE INDENT if ( l <= ord ( i ) and ord ( i ) <= r ) : NEW_LINE INDENT cnt = cnt + 1 NEW_LINE print ( i , end = " β " ) NEW_LINE DEDENT DEDENT return cnt NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT str1 = " geeksforgeeks " NEW_LINE l = 102 NEW_LINE r = 111 NEW_LINE print ( " Characters β with β ASCII β values β " + " in β the β range β [ l , β r ] β are " ) NEW_LINE print ( " and their count is " , CountCharacters ( str1 , l , r ) ) NEW_LINE DEDENT |
Minimum steps to remove substring 010 from a binary string | Function to find the minimum steps ; substring "010" found ; Get the binary string ; Find the minimum steps | def minSteps ( str ) : NEW_LINE INDENT count = 0 NEW_LINE i = 0 NEW_LINE while i < len ( str ) - 2 : NEW_LINE INDENT if str [ i ] == '0' : NEW_LINE INDENT if ( str [ i + 1 ] == '1' ) : NEW_LINE INDENT if ( str [ i + 2 ] == '0' ) : NEW_LINE INDENT count = count + 1 NEW_LINE i = i + 2 NEW_LINE DEDENT DEDENT DEDENT i = i + 1 NEW_LINE DEDENT return count NEW_LINE DEDENT str = "0101010" NEW_LINE print ( minSteps ( str ) ) NEW_LINE |
XOR of Prime Frequencies of Characters in a String | Python3 program to find XOR of Prime Frequencies of Characters in a String ; Function to create Sieve to check primes ; False here indicates that it is not prime ; If prime [ p ] is not changed , then it is a prime ; Update all multiples of p , set them to non - prime ; Function to find XOR of prime frequencies ; map is used to store character frequencies ; Traverse the map ; Calculate XOR of all prime frequencies ; Driver code | from collections import defaultdict NEW_LINE def SieveOfEratosthenes ( prime , p_size ) : NEW_LINE INDENT prime [ 0 ] = False NEW_LINE prime [ 1 ] = False NEW_LINE p = 2 NEW_LINE while p * p <= p_size : NEW_LINE INDENT if prime [ p ] : NEW_LINE INDENT for i in range ( p * 2 , p_size + 1 , p ) : NEW_LINE INDENT prime [ i ] = False NEW_LINE DEDENT DEDENT p += 1 NEW_LINE DEDENT DEDENT def xorOfPrime ( s ) : NEW_LINE INDENT prime = [ True ] * 100005 NEW_LINE SieveOfEratosthenes ( prime , 10005 ) NEW_LINE m = defaultdict ( lambda : 0 ) NEW_LINE for i in range ( 0 , len ( s ) ) : NEW_LINE INDENT m [ s [ i ] ] += 1 NEW_LINE DEDENT result = flag = 0 NEW_LINE for it in m : NEW_LINE INDENT if prime [ m [ it ] ] : NEW_LINE INDENT result ^= m [ it ] NEW_LINE flag = 1 NEW_LINE DEDENT DEDENT if not flag : NEW_LINE INDENT return - 1 NEW_LINE DEDENT return result NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT s = " gggggeeekkkks " NEW_LINE print ( xorOfPrime ( s ) ) NEW_LINE DEDENT |
Count of alphabets having ASCII value less than and greater than k | Function to count the number of characters whose ascii value is less than k ; Initialising the count to 0 ; Incrementing the count if the value is less ; return the count ; Driver code | def CountCharacters ( str , k ) : NEW_LINE INDENT cnt = 0 NEW_LINE l = len ( str ) NEW_LINE for i in range ( l ) : NEW_LINE INDENT if ( ord ( str [ i ] ) < k ) : NEW_LINE INDENT cnt += 1 NEW_LINE DEDENT DEDENT return cnt NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT str = " GeeksForGeeks " NEW_LINE k = 90 NEW_LINE count = CountCharacters ( str , k ) NEW_LINE print ( " Characters β with β ASCII β values " , " less β than β K β are " , count ) NEW_LINE print ( " Characters β with β ASCII β values " , " greater β than β or β equal β to β K β are " , len ( str ) - count ) NEW_LINE DEDENT |
De Bruijn sequence | Set 1 | Python3 implementation of the above approach ; Modified DFS in which no edge is traversed twice ; Function to find a de Bruijn sequence of order n on k characters ; Clearing global variables ; Number of edges ; Driver code | import math NEW_LINE seen = set ( ) NEW_LINE edges = [ ] NEW_LINE def dfs ( node , k , A ) : NEW_LINE INDENT for i in range ( k ) : NEW_LINE INDENT str = node + A [ i ] NEW_LINE if ( str not in seen ) : NEW_LINE INDENT seen . add ( str ) NEW_LINE dfs ( str [ 1 : ] , k , A ) NEW_LINE edges . append ( i ) NEW_LINE DEDENT DEDENT DEDENT def deBruijn ( n , k , A ) : NEW_LINE INDENT seen . clear ( ) NEW_LINE edges . clear ( ) NEW_LINE startingNode = A [ 0 ] * ( n - 1 ) NEW_LINE dfs ( startingNode , k , A ) NEW_LINE S = " " NEW_LINE l = int ( math . pow ( k , n ) ) NEW_LINE for i in range ( l ) : NEW_LINE INDENT S += A [ edges [ i ] ] NEW_LINE DEDENT S += startingNode NEW_LINE return S NEW_LINE DEDENT n = 3 NEW_LINE k = 2 NEW_LINE A = "01" NEW_LINE print ( deBruijn ( n , k , A ) ) NEW_LINE |
Number of words in a camelcase sequence | Function to find the count of words in a CamelCase sequence ; Driver code | def countWords ( str ) : NEW_LINE INDENT count = 1 NEW_LINE for i in range ( 1 , len ( str ) - 1 ) : NEW_LINE INDENT if ( str [ i ] . isupper ( ) ) : NEW_LINE INDENT count += 1 NEW_LINE DEDENT DEDENT return count NEW_LINE DEDENT str = " geeksForGeeks " ; NEW_LINE print ( countWords ( str ) ) NEW_LINE |
Check whether frequency of characters in a string makes Fibonacci Sequence | Python3 program to check whether the frequency of characters in a string make Fibonacci Sequence ; Function to check if the frequencies are in Fibonacci series ; map to store the frequencies of character ; Vector to store first n fibonacci numbers ; Get the size of the map ; a and b are first and second terms of fibonacci series ; vector v contains elements of fibonacci series ; Compare vector elements with values in Map ; Driver code | from collections import defaultdict NEW_LINE def isFibonacci ( s ) : NEW_LINE INDENT m = defaultdict ( lambda : 0 ) NEW_LINE for i in range ( 0 , len ( s ) ) : NEW_LINE INDENT m [ s [ i ] ] += 1 NEW_LINE DEDENT v = [ ] NEW_LINE n = len ( m ) NEW_LINE a = b = 1 NEW_LINE v . append ( a ) NEW_LINE v . append ( b ) NEW_LINE for i in range ( 0 , n - 2 ) : NEW_LINE INDENT v . append ( a + b ) NEW_LINE c = a + b NEW_LINE a , b = b , c NEW_LINE DEDENT flag , i = 1 , 0 NEW_LINE for itr in sorted ( m ) : NEW_LINE INDENT if m [ itr ] != v [ i ] : NEW_LINE INDENT flag = 0 NEW_LINE break NEW_LINE DEDENT i += 1 NEW_LINE DEDENT if flag == 1 : NEW_LINE INDENT return " YES " NEW_LINE DEDENT else : NEW_LINE INDENT return " NO " NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT s = " abeeedd " NEW_LINE print ( isFibonacci ( s ) ) NEW_LINE DEDENT |
Lexicographically smallest string formed by removing at most one character | Function to return the smallest string ; iterate the string ; first point where s [ i ] > s [ i + 1 ] ; append the string without i - th character in it ; leave the last character ; Driver Code | def smallest ( s ) : NEW_LINE INDENT l = len ( s ) NEW_LINE ans = " " NEW_LINE for i in range ( l - 1 ) : NEW_LINE INDENT if ( s [ i ] > s [ i + 1 ] ) : NEW_LINE INDENT for j in range ( l ) : NEW_LINE INDENT if ( i != j ) : NEW_LINE INDENT ans += s [ j ] NEW_LINE DEDENT DEDENT return ans NEW_LINE DEDENT DEDENT ans = s [ 0 : l - 1 ] NEW_LINE return ans NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT s = " abcda " NEW_LINE print ( smallest ( s ) ) NEW_LINE DEDENT |
Arrangement of the characters of a word such that all vowels are at odd places | Python3 program to find the number of ways in which the characters of the word can be arranged such that the vowels occupy only the odd positions ; Function to return the factorial of a number ; calculating nPr ; Function to find the number of ways in which the characters of the word can be arranged such that the vowels occupy only the odd positions ; Get total even positions ; Get total odd positions ; Store frequency of each character of the string ; Count total number of vowels ; Count total number of consonants ; Calculate the total number of ways ; Driver code | import math NEW_LINE def fact ( n ) : NEW_LINE INDENT f = 1 ; NEW_LINE for i in range ( 2 , n + 1 ) : NEW_LINE INDENT f = f * i ; NEW_LINE DEDENT return f ; NEW_LINE DEDENT def npr ( n , r ) : NEW_LINE INDENT return fact ( n ) / fact ( n - r ) ; NEW_LINE DEDENT def countPermutations ( str ) : NEW_LINE INDENT even = math . floor ( len ( str ) / 2 ) ; NEW_LINE odd = len ( str ) - even ; NEW_LINE ways = 0 ; NEW_LINE freq = [ 0 ] * 26 ; NEW_LINE for i in range ( len ( str ) ) : NEW_LINE INDENT freq [ ord ( str [ i ] ) - ord ( ' a ' ) ] += 1 ; NEW_LINE DEDENT nvowels = ( freq [ 0 ] + freq [ 4 ] + freq [ 8 ] + freq [ 14 ] + freq [ 20 ] ) ; NEW_LINE nconsonants = len ( str ) - nvowels ; NEW_LINE ways = ( npr ( odd , nvowels ) * npr ( nconsonants , nconsonants ) ) ; NEW_LINE return int ( ways ) ; NEW_LINE DEDENT str = " geeks " ; NEW_LINE print ( countPermutations ( str ) ) ; NEW_LINE |
Replace all consonants with nearest vowels in a string | Function to replace consonant with nearest vowels ; Driver code | def replacingConsonants ( s ) : NEW_LINE INDENT nVowel = " aaaeeeeiiiiioooooouuuuuuuu " NEW_LINE for i in range ( 0 , len ( s ) ) : NEW_LINE INDENT s = s . replace ( s [ i ] , nVowel [ ord ( s [ i ] ) - 97 ] ) NEW_LINE DEDENT return s NEW_LINE DEDENT s = " geeksforgeeks " ; NEW_LINE print ( replacingConsonants ( s ) ) ; NEW_LINE |
Replace consonants with next immediate consonants alphabetically in a String | Function to check if a character is vowel or not ; Function that replaces consonant with next immediate consonant alphabatically ; Start traversing the string ; if character is z , than replace it with character b ; if the alphabet is not z ; replace the element with next immediate alphabet ; if next immediate alphabet is vowel , than take next 2 nd immediate alphabet ( since no two vowels occurs consecutively in alphabets ) hence no further checking is required ; Driver code | def isVowel ( ch ) : NEW_LINE INDENT if ( ch != ' a ' and ch != ' e ' and ch != ' i ' and ch != ' o ' and ch != ' u ' ) : NEW_LINE INDENT return False ; NEW_LINE DEDENT return True ; NEW_LINE DEDENT def replaceConsonants ( s ) : NEW_LINE INDENT for i in range ( len ( s ) ) : NEW_LINE INDENT if ( isVowel ( s [ i ] ) == False ) : NEW_LINE INDENT if ( s [ i ] == ' z ' ) : NEW_LINE INDENT s [ i ] = ' b ' ; NEW_LINE DEDENT else : NEW_LINE INDENT s [ i ] = chr ( ord ( s [ i ] ) + 1 ) ; NEW_LINE if ( isVowel ( s [ i ] ) == True ) : NEW_LINE INDENT s [ i ] = chr ( ord ( s [ i ] ) + 1 ) ; NEW_LINE DEDENT DEDENT DEDENT DEDENT return ' ' . join ( s ) ; NEW_LINE DEDENT s = " geeksforgeeks " ; NEW_LINE print ( replaceConsonants ( list ( s ) ) ) ; NEW_LINE |
Remove characters from string that appears strictly less than K times | Python 3 program to reduce the string by removing the characters which appears less than k times ; Function to reduce the string by removing the characters which appears less than k times ; Hash table initialised to 0 ; Increment the frequency of the character ; create a new empty string ; Append the characters which appears more than equal to k times ; Driver Code | MAX_CHAR = 26 NEW_LINE def removeChars ( str , k ) : NEW_LINE INDENT hash = [ 0 ] * ( MAX_CHAR ) NEW_LINE n = len ( str ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT hash [ ord ( str [ i ] ) - ord ( ' a ' ) ] += 1 NEW_LINE DEDENT res = " " NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( hash [ ord ( str [ i ] ) - ord ( ' a ' ) ] >= k ) : NEW_LINE INDENT res += str [ i ] NEW_LINE DEDENT DEDENT return res NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT str = " geeksforgeeks " NEW_LINE k = 2 NEW_LINE print ( removeChars ( str , k ) ) NEW_LINE DEDENT |
Count changes in Led Lights to display digits one by one | Python3 program to count number of on offs to display digits of a number . ; store the led lights required to display a particular number . ; compute the change in led and keep on adding the change ; Driver code | def countOnOff ( n ) : NEW_LINE INDENT Led = [ 6 , 2 , 5 , 5 , 4 , 5 , 6 , 3 , 7 , 5 ] NEW_LINE leng = len ( n ) NEW_LINE sum = Led [ int ( n [ 0 ] ) - int ( '0' ) ] NEW_LINE for i in range ( 1 , leng ) : NEW_LINE INDENT sum = ( sum + abs ( Led [ int ( n [ i ] ) - int ( '0' ) ] - Led [ int ( n [ i - 1 ] ) - int ( '0' ) ] ) ) NEW_LINE DEDENT return sum NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT n = "082" NEW_LINE print ( countOnOff ( n ) ) NEW_LINE DEDENT |
Program to check if all characters have even frequency | Python implementation of the above approach ; creating a frequency array ; Finding length of s ; counting frequency of all characters ; checking if any odd frequency is there or not ; Driver code | def check ( s ) : NEW_LINE INDENT freq = [ 0 ] * 26 NEW_LINE n = len ( s ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT freq [ ord ( s [ i ] ) - 97 ] += 1 NEW_LINE DEDENT for i in range ( 26 ) : NEW_LINE INDENT if ( freq [ i ] % 2 == 1 ) : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT return True NEW_LINE DEDENT s = " abaccaba " NEW_LINE if ( check ( s ) ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT |
Maximum Consecutive Zeroes in Concatenated Binary String | returns the maximum size of a substring consisting only of zeroes after k concatenation ; stores the maximum length of the required substring ; if the current character is 0 ; stores maximum length of current substrings with zeroes ; if the whole is filled with zero ; computes the length of the maximal prefix which contains only zeroes ; computes the length of the maximal suffix which contains only zeroes ; if more than 1 concatenations are to be made ; Driver code | def max_length_substring ( st , n , k ) : NEW_LINE INDENT max_len = 0 NEW_LINE len = 0 NEW_LINE for i in range ( 0 , n ) : NEW_LINE INDENT if ( st [ i ] == '0' ) : NEW_LINE INDENT len = len + 1 ; NEW_LINE DEDENT else : NEW_LINE INDENT len = 0 NEW_LINE DEDENT max_len = max ( max_len , len ) NEW_LINE DEDENT if ( max_len == n ) : NEW_LINE INDENT return n * k NEW_LINE DEDENT pref = 0 NEW_LINE suff = 0 NEW_LINE i = 0 NEW_LINE while ( st [ i ] == '0' ) : NEW_LINE INDENT i = i + 1 NEW_LINE pref = pref + 1 NEW_LINE DEDENT i = n - 1 NEW_LINE while ( st [ i ] == '0' ) : NEW_LINE INDENT i = i - 1 NEW_LINE suff = suff + 1 NEW_LINE DEDENT if ( k > 1 ) : NEW_LINE INDENT max_len = max ( max_len , pref + suff ) NEW_LINE DEDENT return max_len NEW_LINE DEDENT n = 6 NEW_LINE k = 3 NEW_LINE st = "110010" NEW_LINE ans = max_length_substring ( st , n , k ) NEW_LINE print ( ans ) NEW_LINE |
Count number of substrings with numeric value greater than X | Function that counts valid sub - strings ; Only take those numbers that do not start with '0' . ; converting the sub - string starting from index ' i ' and having length ' len ' to int and checking if it is greater than X or not ; Driver code | def countSubStr ( S , X ) : NEW_LINE INDENT cnt = 0 NEW_LINE N = len ( S ) NEW_LINE for i in range ( 0 , N ) : NEW_LINE INDENT if ( S [ i ] != '0' ) : NEW_LINE INDENT j = 1 NEW_LINE while ( ( j + i ) <= N ) : NEW_LINE INDENT num = int ( S [ i : i + j ] ) NEW_LINE if ( num > X ) : NEW_LINE INDENT cnt = cnt + 1 NEW_LINE DEDENT j = j + 1 NEW_LINE DEDENT DEDENT DEDENT return cnt ; NEW_LINE DEDENT S = "2222" ; NEW_LINE X = 97 ; NEW_LINE print ( countSubStr ( S , X ) ) NEW_LINE |
Check whether a binary string can be formed by concatenating given N numbers sequentially | Function that returns false if the number passed as argument contains digit ( s ) other than '0' or '1 ; Function that checks whether the binary string can be formed or not ; Empty string for storing the binary number ; check if a [ i ] can be a part of the binary string ; Conversion of int into string ; if a [ i ] can 't be a part then break the loop ; possible to create binary string ; impossible to create binary string ; Driver code | ' NEW_LINE def isBinary ( n ) : NEW_LINE INDENT while n != 0 : NEW_LINE INDENT temp = n % 10 NEW_LINE if temp != 0 and temp != 1 : NEW_LINE INDENT return False NEW_LINE DEDENT n = n // 10 NEW_LINE DEDENT return True NEW_LINE DEDENT def formBinaryStr ( n , a ) : NEW_LINE INDENT flag = True NEW_LINE s = " " NEW_LINE for i in range ( 0 , n ) : NEW_LINE INDENT if isBinary ( a [ i ] ) == True : NEW_LINE INDENT s += str ( a [ i ] ) NEW_LINE DEDENT else : NEW_LINE INDENT flag = False NEW_LINE break NEW_LINE DEDENT DEDENT if flag == True : NEW_LINE INDENT print ( s ) NEW_LINE DEDENT else : NEW_LINE INDENT cout << " - 1 NEW_LINE DEDENT DEDENT " NEW_LINE if __name__ == " _ _ main _ _ " : NEW_LINE INDENT a = [ 10 , 1 , 0 , 11 , 10 ] NEW_LINE N = len ( a ) NEW_LINE formBinaryStr ( N , a ) NEW_LINE DEDENT |
Check if all the palindromic sub | Function to check if the string is palindrome ; Function that checks whether all the palindromic sub - strings are of odd length . ; Creating each substring ; If the sub - string is of even length and is a palindrome then , we return False ; Driver code | def checkPalindrome ( s ) : NEW_LINE INDENT for i in range ( len ( s ) ) : NEW_LINE INDENT if ( s [ i ] != s [ len ( s ) - i - 1 ] ) : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT return True NEW_LINE DEDENT def CheckOdd ( s ) : NEW_LINE INDENT n = len ( s ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT x = " " NEW_LINE for j in range ( i , n ) : NEW_LINE INDENT x += s [ j ] NEW_LINE if ( len ( x ) % 2 == 0 and checkPalindrome ( x ) == True ) : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT DEDENT return True NEW_LINE DEDENT s = " geeksforgeeks " NEW_LINE if ( CheckOdd ( s ) ) : NEW_LINE INDENT print ( " YES " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " NO " ) NEW_LINE DEDENT |
Number of permutations of a string in which all the occurrences of a given character occurs together | Function to return factorial of the number passed as argument ; Function to get the total permutations which satisfy the given condition ; Create has to store count of each character ; Store character occurrences ; Count number of times Particular character comes ; If particular character isn 't present in the string then return 0 ; Remove count of particular character ; Total length of the string ; Assume all occurrences of particular character as a single character . ; Compute factorial of the length ; Divide by the factorials of the no . of occurrences of all the characters . ; return the result ; Driver code ; Assuming the string and the character are all in uppercase | def fact ( n ) : NEW_LINE INDENT result = 1 NEW_LINE for i in range ( 1 , n + 1 ) : NEW_LINE INDENT result *= i NEW_LINE DEDENT return result NEW_LINE DEDENT def getResult ( string , ch ) : NEW_LINE INDENT has = [ 0 ] * 26 NEW_LINE for i in range ( len ( string ) ) : NEW_LINE INDENT has [ ord ( string [ i ] ) - ord ( ' A ' ) ] += 1 NEW_LINE DEDENT particular = has [ ord ( ch ) - ord ( ' A ' ) ] NEW_LINE if particular == 0 : NEW_LINE INDENT return 0 NEW_LINE DEDENT has [ ord ( ch ) - ord ( ' A ' ) ] = 0 NEW_LINE total = len ( string ) NEW_LINE total = total - particular + 1 NEW_LINE result = fact ( total ) NEW_LINE for i in range ( 26 ) : NEW_LINE INDENT if has [ i ] > 1 : NEW_LINE INDENT result /= fact ( has [ i ] ) NEW_LINE DEDENT DEDENT return result NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT string = " MISSISSIPPI " NEW_LINE print ( getResult ( string , ' S ' ) ) NEW_LINE DEDENT |
Check if there exists any sub | Function to check if there exists at least 1 sub - sequence in a string which is not palindrome ; use set to count number of distinct characters ; insert each character in set ; If there is more than 1 unique characters , return true ; Else , return false ; Driver code | def isAnyNotPalindrome ( s ) : NEW_LINE INDENT unique = set ( ) NEW_LINE for i in range ( 0 , len ( s ) ) : NEW_LINE INDENT unique . add ( s [ i ] ) NEW_LINE DEDENT if ( len ( unique ) > 1 ) : NEW_LINE INDENT return True NEW_LINE DEDENT else : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT s = " aaaaab " NEW_LINE if ( isAnyNotPalindrome ( s ) ) : NEW_LINE INDENT print ( " YES " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " NO " ) NEW_LINE DEDENT DEDENT |
Arrangement of words without changing the relative position of vowel and consonants | this function return n ! ; this will return total number of ways ; freq maintains frequency of each character in word ; check character is vowel or not ; the characters that are not vowel must be consonant ; number of ways to arrange vowel ; multiply both as these are independent ; string contains only capital letters ; this will contain ans | def factorial ( n ) : NEW_LINE INDENT res = 1 NEW_LINE for i in range ( 1 , n + 1 ) : NEW_LINE INDENT res = res * i NEW_LINE DEDENT return res NEW_LINE DEDENT def count ( word ) : NEW_LINE INDENT freq = [ 0 for i in range ( 30 ) ] NEW_LINE vowel = 0 NEW_LINE consonant = 0 NEW_LINE for i in range ( len ( word ) ) : NEW_LINE INDENT freq [ ord ( word [ i ] ) - 65 ] += 1 NEW_LINE if ( word [ i ] == ' A ' or word [ i ] == ' E ' or word [ i ] == ' I ' or word [ i ] == ' O ' or word [ i ] == ' U ' ) : NEW_LINE INDENT vowel += 1 NEW_LINE DEDENT else : NEW_LINE INDENT consonant += 1 NEW_LINE DEDENT DEDENT vowelArrange = factorial ( vowel ) NEW_LINE vowelArrange //= factorial ( freq [ 0 ] ) NEW_LINE vowelArrange //= factorial ( freq [ 4 ] ) NEW_LINE vowelArrange //= factorial ( freq [ 8 ] ) NEW_LINE vowelArrange //= factorial ( freq [ 14 ] ) NEW_LINE vowelArrange //= factorial ( freq [ 20 ] ) NEW_LINE consonantArrange = factorial ( consonant ) NEW_LINE for i in range ( 26 ) : NEW_LINE INDENT if ( i != 0 and i != 4 and i != 8 and i != 14 and i != 20 ) : NEW_LINE INDENT consonantArrange //= factorial ( freq [ i ] ) NEW_LINE DEDENT DEDENT total = vowelArrange * consonantArrange NEW_LINE return total NEW_LINE DEDENT word = " COMPUTER " NEW_LINE ans = count ( word ) NEW_LINE print ( ans ) NEW_LINE |
Check if it is possible to create a palindrome string from given N | Function to check if a string is palindrome or not ; String that stores characters of s in reverse order ; Length of the string s ; String used to form substring using N ; Variable to store sum of digits of N ; Forming the substring by traversing N ; Appending the substr to str till it 's length becomes equal to sum ; Trimming the string str so that it 's length becomes equal to sum ; Driver code ; Calling function isPalindrome to check if str is Palindrome or not | def isPalindrome ( s ) : NEW_LINE INDENT s1 = " " NEW_LINE N = len ( s ) NEW_LINE i = ( N - 1 ) NEW_LINE while ( i >= 0 ) : NEW_LINE INDENT s1 += s [ i ] NEW_LINE i = i - 1 NEW_LINE DEDENT if ( s == s1 ) : NEW_LINE INDENT return True NEW_LINE DEDENT return False NEW_LINE DEDENT def createString ( N ) : NEW_LINE INDENT s2 = " " NEW_LINE s = str ( N ) NEW_LINE letters = " abcdefghij " NEW_LINE sum = 0 NEW_LINE substr = " " NEW_LINE for i in range ( 0 , len ( s ) ) : NEW_LINE INDENT digit = int ( s [ i ] ) NEW_LINE substr += letters [ digit ] NEW_LINE sum += digit NEW_LINE DEDENT while ( len ( s2 ) <= sum ) : NEW_LINE INDENT s2 += substr NEW_LINE DEDENT s2 = s2 [ : sum ] NEW_LINE return isPalindrome ( s2 ) NEW_LINE DEDENT N = 61 ; NEW_LINE flag = createString ( N ) NEW_LINE if ( flag ) : NEW_LINE INDENT print ( " YES " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " NO " ) NEW_LINE DEDENT |
Program to find the product of ASCII values of characters in a string | Function to find product of ASCII value of characters in string ; Traverse string to find the product ; Return the product ; Driver code | def productAscii ( str ) : NEW_LINE INDENT prod = 1 NEW_LINE for i in range ( 0 , len ( str ) ) : NEW_LINE INDENT prod = prod * ord ( str [ i ] ) NEW_LINE DEDENT return prod NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT str = " GfG " NEW_LINE print ( productAscii ( str ) ) NEW_LINE DEDENT |
Balance a string after removing extra brackets | Print balanced and remove extra brackets from string ; Maintain a count for opening brackets Traversing string ; check if opening bracket ; print str [ i ] and increment count by 1 ; check if closing bracket and count != 0 ; decrement count by 1 ; if str [ i ] not a closing brackets print it ; balanced brackets if opening brackets are more then closing brackets ; print remaining closing brackets ; Driver code | def balancedString ( str ) : NEW_LINE INDENT count , i = 0 , 0 NEW_LINE n = len ( str ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( str [ i ] == ' ( ' ) : NEW_LINE INDENT print ( str [ i ] , end = " " ) NEW_LINE count += 1 NEW_LINE DEDENT elif ( str [ i ] == ' ) ' and count != 0 ) : NEW_LINE INDENT print ( str [ i ] , end = " " ) NEW_LINE count -= 1 NEW_LINE DEDENT elif ( str [ i ] != ' ) ' ) : NEW_LINE INDENT print ( str [ i ] , end = " " ) NEW_LINE DEDENT DEDENT if ( count != 0 ) : NEW_LINE INDENT for i in range ( count ) : NEW_LINE INDENT print ( " ) " , end = " " ) NEW_LINE DEDENT DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : str = " gau ) ra ) v ( ku ( mar ( rajput ) ) " NEW_LINE INDENT balancedString ( str ) NEW_LINE DEDENT |
Minimum operation require to make first and last character same | Python3 program to minimum operation require to make first and last character same ; Recursive function call ; Decrement ending index only ; Increment starting index only ; Increment starting index and decrement index ; Driver code ; Function call | import sys NEW_LINE MAX = sys . maxsize NEW_LINE def minOperation ( s , i , j , count ) : NEW_LINE INDENT if ( ( i >= len ( s ) and j < 0 ) or ( i == j ) ) : NEW_LINE INDENT return MAX NEW_LINE DEDENT if ( s [ i ] == s [ j ] ) : NEW_LINE INDENT return count NEW_LINE DEDENT if ( i >= len ( s ) ) : NEW_LINE INDENT return minOperation ( s , i , j - 1 , count + 1 ) NEW_LINE DEDENT elif ( j < 0 ) : NEW_LINE INDENT return minOperation ( s , i + 1 , j , count + 1 ) NEW_LINE DEDENT else : NEW_LINE INDENT return min ( minOperation ( s , i , j - 1 , count + 1 ) , minOperation ( s , i + 1 , j , count + 1 ) ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT s = " bacdefghipalop " NEW_LINE ans = minOperation ( s , 0 , len ( s ) - 1 , 0 ) NEW_LINE if ( ans == MAX ) : NEW_LINE INDENT print ( - 1 ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( ans ) NEW_LINE DEDENT DEDENT |
Count strings with consonants and vowels at alternate position | Function to find the count of strings ; Variable to store the final result ; Loop iterating through string ; If ' $ ' is present at the even position in the string ; ' sum ' is multiplied by 21 ; If ' $ ' is present at the odd position in the string ; ' sum ' is multiplied by 5 ; Driver code ; Let the string ' str ' be s$$e$ ; Print result | def countStrings ( s ) : NEW_LINE INDENT sum = 1 NEW_LINE for i in range ( len ( s ) ) : NEW_LINE INDENT if ( i % 2 == 0 and s [ i ] == ' $ ' ) : NEW_LINE INDENT sum *= 21 NEW_LINE DEDENT elif ( s [ i ] == ' $ ' ) : NEW_LINE INDENT sum *= 5 NEW_LINE DEDENT DEDENT return sum NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT str = " s $ $ e $ " NEW_LINE print ( countStrings ( str ) ) NEW_LINE DEDENT |
Remove duplicates from a string in O ( 1 ) extra space | Function to remove duplicates ; keeps track of visited characters ; gets character value ; keeps track of length of resultant string ; check if Xth bit of counter is unset ; mark current character as visited ; Driver code | def removeDuplicatesFromString ( str2 ) : NEW_LINE INDENT counter = 0 ; NEW_LINE i = 0 ; NEW_LINE size = len ( str2 ) ; NEW_LINE str1 = list ( str2 ) ; NEW_LINE x = 0 ; NEW_LINE length = 0 ; NEW_LINE while ( i < size ) : NEW_LINE INDENT x = ord ( str1 [ i ] ) - 97 ; NEW_LINE if ( ( counter & ( 1 << x ) ) == 0 ) : NEW_LINE INDENT str1 [ length ] = chr ( 97 + x ) ; NEW_LINE counter = counter | ( 1 << x ) ; NEW_LINE length += 1 ; NEW_LINE DEDENT i += 1 ; NEW_LINE DEDENT str2 = ' ' . join ( str1 ) ; NEW_LINE return str2 [ 0 : length ] ; NEW_LINE DEDENT str1 = " geeksforgeeks " ; NEW_LINE print ( removeDuplicatesFromString ( str1 ) ) ; NEW_LINE |
Remove duplicates from a string in O ( 1 ) extra space | Method to remove duplicates ; Table to keep track of visited characters ; To keep track of end index of resultant string ; Driver code | def removeDuplicatesFromString ( string ) : NEW_LINE INDENT table = [ 0 for i in range ( 256 ) ] NEW_LINE endIndex = 0 NEW_LINE string = list ( string ) NEW_LINE for i in range ( len ( string ) ) : NEW_LINE INDENT if ( table [ ord ( string [ i ] ) ] == 0 ) : NEW_LINE INDENT table [ ord ( string [ i ] ) ] = - 1 NEW_LINE string [ endIndex ] = string [ i ] NEW_LINE endIndex += 1 NEW_LINE DEDENT DEDENT ans = " " NEW_LINE for i in range ( endIndex ) : NEW_LINE ans += string [ i ] NEW_LINE return ans NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT temp = " geeksforgeeks " NEW_LINE print ( removeDuplicatesFromString ( temp ) ) NEW_LINE DEDENT |
Check if the characters in a string form a Palindrome in O ( 1 ) extra space | Utility function to get the position of first character in the string ; Get the position of first character in the string ; Utility function to get the position of last character in the string ; Get the position of last character in the string ; Function to check if the characters in the given string forms a Palindrome in O ( 1 ) extra space ; break , when all letters are checked ; if mismatch found , break the loop ; Driver code | def firstPos ( str , start , end ) : NEW_LINE INDENT firstChar = - 1 NEW_LINE for i in range ( start , end + 1 ) : NEW_LINE INDENT if ( str [ i ] >= ' a ' and str [ i ] <= ' z ' ) : NEW_LINE INDENT firstChar = i NEW_LINE break NEW_LINE DEDENT DEDENT return firstChar NEW_LINE DEDENT def lastPos ( str , start , end ) : NEW_LINE INDENT lastChar = - 1 NEW_LINE for i in range ( start , end - 1 , - 1 ) : NEW_LINE INDENT if ( str [ i ] >= ' a ' and str [ i ] <= ' z ' ) : NEW_LINE INDENT lastChar = i NEW_LINE break NEW_LINE DEDENT DEDENT return lastChar NEW_LINE DEDENT def isPalindrome ( str ) : NEW_LINE INDENT firstChar = 0 NEW_LINE lastChar = len ( str ) - 1 NEW_LINE ch = True NEW_LINE for i in range ( len ( str ) ) : NEW_LINE INDENT firstChar = firstPos ( str , firstChar , lastChar ) ; NEW_LINE lastChar = lastPos ( str , lastChar , firstChar ) ; NEW_LINE if ( lastChar < 0 or firstChar < 0 ) : NEW_LINE INDENT break NEW_LINE DEDENT if ( str [ firstChar ] == str [ lastChar ] ) : NEW_LINE INDENT firstChar += 1 NEW_LINE lastChar -= 1 NEW_LINE continue NEW_LINE DEDENT ch = False NEW_LINE break NEW_LINE DEDENT return ( ch ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT str = " m TABSYMBOL a β 343 β la β y β a β l β am " NEW_LINE if ( isPalindrome ( str ) ) : NEW_LINE INDENT print ( " YES " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " NO " ) NEW_LINE DEDENT DEDENT |
Maximum length subsequence possible of the form R ^ N K ^ N | Function to calculate the maximum length of substring of the form R ^ nK ^ n ; Count no . Of R 's before a K ; Count no . Of K 's after a K ; Update maximum length ; Driver code | def find ( s ) : NEW_LINE INDENT Max = j = countk = countr = 0 NEW_LINE table = [ [ 0 , 0 ] for i in range ( len ( s ) ) ] NEW_LINE for i in range ( 0 , len ( s ) ) : NEW_LINE INDENT if s [ i ] == ' R ' : NEW_LINE INDENT countr += 1 NEW_LINE DEDENT else : NEW_LINE INDENT table [ j ] [ 0 ] = countr NEW_LINE j += 1 NEW_LINE DEDENT DEDENT j -= 1 NEW_LINE for i in range ( len ( s ) - 1 , - 1 , - 1 ) : NEW_LINE INDENT if s [ i ] == ' K ' : NEW_LINE INDENT countk += 1 NEW_LINE table [ j ] [ 1 ] = countk NEW_LINE j -= 1 NEW_LINE DEDENT if min ( table [ j + 1 ] [ 0 ] , table [ j + 1 ] [ 1 ] ) > Max : NEW_LINE INDENT Max = min ( table [ j + 1 ] [ 0 ] , table [ j + 1 ] [ 1 ] ) NEW_LINE DEDENT DEDENT return Max NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT s = " RKRRRKKRRKKKKRR " NEW_LINE print ( find ( s ) ) NEW_LINE DEDENT |
Longest common anagram subsequence from N strings | Function to store frequency of each character in each string ; Function to Find longest possible sequence of N strings which is anagram to each other ; to get lexicographical largest sequence . ; find minimum of that character ; print that character minimum number of times ; Driver code ; to store frequency of each character in each string ; To get frequency of each character ; Function call | def frequency ( fre , s , n ) : NEW_LINE INDENT for i in range ( 0 , n ) : NEW_LINE INDENT string = s [ i ] NEW_LINE for j in range ( 0 , len ( string ) ) : NEW_LINE INDENT fre [ i ] [ ord ( string [ j ] ) - ord ( ' a ' ) ] += 1 NEW_LINE DEDENT DEDENT DEDENT def LongestSequence ( fre , n ) : NEW_LINE INDENT for i in range ( MAX_CHAR - 1 , - 1 , - 1 ) : NEW_LINE INDENT mi = fre [ 0 ] [ i ] NEW_LINE for j in range ( 1 , n ) : NEW_LINE INDENT mi = min ( fre [ j ] [ i ] , mi ) NEW_LINE DEDENT while mi : NEW_LINE INDENT print ( chr ( ord ( ' a ' ) + i ) , end = " " ) NEW_LINE mi -= 1 NEW_LINE DEDENT DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT s = [ " loo " , " lol " , " olive " ] NEW_LINE n = len ( s ) NEW_LINE MAX_CHAR = 26 NEW_LINE fre = [ [ 0 for i in range ( 26 ) ] for j in range ( n ) ] NEW_LINE frequency ( fre , s , n ) NEW_LINE LongestSequence ( fre , n ) NEW_LINE DEDENT |
Check if two strings are permutation of each other | function to check whether two strings are Permutation of each other ; Get lengths of both strings ; If length of both strings is not same , then they cannot be Permutation ; Sort both strings ; Compare sorted strings ; Driver Code | def arePermutation ( str1 , str2 ) : NEW_LINE INDENT n1 = len ( str1 ) NEW_LINE n2 = len ( str2 ) NEW_LINE if ( n1 != n2 ) : NEW_LINE INDENT return False NEW_LINE DEDENT a = sorted ( str1 ) NEW_LINE str1 = " β " . join ( a ) NEW_LINE b = sorted ( str2 ) NEW_LINE str2 = " β " . join ( b ) NEW_LINE for i in range ( 0 , n1 , 1 ) : NEW_LINE INDENT if ( str1 [ i ] != str2 [ i ] ) : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT return True NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT str1 = " test " NEW_LINE str2 = " ttew " NEW_LINE if ( arePermutation ( str1 , str2 ) ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT DEDENT |
Check if two strings are permutation of each other | Python3 function to check whether two strings are Permutations of each other ; Create a count array and initialize all values as 0 ; For each character in input strings , increment count in the corresponding count array ; If both strings are of different length . Removing this condition will make the program fail for strings like " aaca " and " aca " ; See if there is any non - zero value in count array | def arePermutation ( str1 , str2 ) : NEW_LINE INDENT count = [ 0 for i in range ( NO_OF_CHARS ) ] NEW_LINE i = 0 NEW_LINE while ( str1 [ i ] and str2 [ i ] ) : NEW_LINE INDENT count [ str1 [ i ] ] += 1 NEW_LINE count [ str2 [ i ] ] -= 1 NEW_LINE DEDENT if ( str1 [ i ] or str2 [ i ] ) : NEW_LINE return False ; NEW_LINE for i in range ( NO_OF_CHARS ) : NEW_LINE INDENT if ( count [ i ] ) : NEW_LINE INDENT return False ; NEW_LINE DEDENT DEDENT return True ; NEW_LINE DEDENT |
Maximum power of jump required to reach the end of string | Function to calculate the maximum power of the jump ; Initialize the count with 1 ; Find the character at last index ; Start traversing the string ; Check if the current char is equal to the last character ; max_so_far stores maximum value of the power of the jump from starting to ith position ; Reset the count to 1 ; Else , increment the number of jumps / count ; Return the maximum number of jumps ; Driver Code | def powerOfJump ( s ) : NEW_LINE INDENT count = 1 NEW_LINE max_so_far = 0 NEW_LINE ch = s [ - 1 ] NEW_LINE for i in range ( 0 , len ( s ) ) : NEW_LINE INDENT if s [ i ] == ch : NEW_LINE INDENT if count > max_so_far : NEW_LINE INDENT max_so_far = count NEW_LINE DEDENT count = 1 NEW_LINE DEDENT else : NEW_LINE INDENT count += 1 NEW_LINE DEDENT DEDENT return max_so_far NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT st = "1010101" NEW_LINE print ( powerOfJump ( st ) ) NEW_LINE DEDENT |
Longest substring with count of 1 s more than 0 s | Function to find longest substring having count of 1 s more than count of 0 s . ; To store sum . ; To store first occurrence of each sum value . ; To store maximum length . ; To store current substring length . ; Add 1 if current character is 1 else subtract 1. ; If sum is positive , then maximum length substring is bin1 [ 0. . i ] ; If sum is negative , then maximum length substring is bin1 [ j + 1. . i ] , where sum of substring bin1 [ 0. . j ] is sum - 1. ; Make entry for this sum value in hash table if this value is not present . ; Driver code | def findLongestSub ( bin1 ) : NEW_LINE INDENT n = len ( bin1 ) NEW_LINE sum = 0 NEW_LINE prevSum = { i : 0 for i in range ( n ) } NEW_LINE maxlen = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( bin1 [ i ] == '1' ) : NEW_LINE INDENT sum += 1 NEW_LINE DEDENT else : NEW_LINE INDENT sum -= 1 NEW_LINE DEDENT if ( sum > 0 ) : NEW_LINE INDENT maxlen = i + 1 NEW_LINE DEDENT elif ( sum <= 0 ) : NEW_LINE INDENT if ( ( sum - 1 ) in prevSum ) : NEW_LINE INDENT currlen = i - prevSum [ sum - 1 ] NEW_LINE maxlen = max ( maxlen , currlen ) NEW_LINE DEDENT DEDENT if ( ( sum ) not in prevSum ) : NEW_LINE INDENT prevSum [ sum ] = i NEW_LINE DEDENT DEDENT return maxlen NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT bin1 = "1010" NEW_LINE print ( findLongestSub ( bin1 ) ) NEW_LINE DEDENT |
Average of ASCII values of characters of a given string | Function to find average of ASCII value of chars ; loop to sum the ascii value of chars ; Returning average of chars ; Driver code | def averageValue ( s ) : NEW_LINE INDENT sum_char = 0 NEW_LINE for i in range ( len ( s ) ) : NEW_LINE INDENT sum_char += ord ( s [ i ] ) NEW_LINE DEDENT return sum_char // len ( s ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT s = " GeeksforGeeks " NEW_LINE print ( averageValue ( s ) ) NEW_LINE DEDENT |
Check if two same sub | Function to check if similar subsequences occur in a string or not ; iterate and count the frequency ; counting frequency of the letters ; check if frequency is more than once of any character ; Driver Code | def check ( s , l ) : NEW_LINE INDENT freq = [ 0 for i in range ( 26 ) ] NEW_LINE for i in range ( l ) : NEW_LINE INDENT freq [ ord ( s [ i ] ) - ord ( ' a ' ) ] += 1 NEW_LINE DEDENT for i in range ( 26 ) : NEW_LINE INDENT if ( freq [ i ] >= 2 ) : NEW_LINE INDENT return True NEW_LINE DEDENT DEDENT return False NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT s = " geeksforgeeks " NEW_LINE l = len ( s ) NEW_LINE if ( check ( s , l ) ) : NEW_LINE INDENT print ( " YES " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " NO " ) NEW_LINE DEDENT DEDENT |
Find the winner of a game where scores are given as a binary string | function for winner prediction ; increase count ; check losing condition ; check winning condition ; check tie on n - 1 point ; increase count ; check for 2 point lead ; condition of lost ; condition of win ; Driver Code | def predictWinner ( score , n ) : NEW_LINE INDENT count = [ 0 for i in range ( 2 ) ] NEW_LINE for i in range ( 0 , len ( score ) , 1 ) : NEW_LINE INDENT index = ord ( score [ i ] ) - ord ( '0' ) NEW_LINE count [ index ] += 1 NEW_LINE if ( count [ 0 ] == n and count [ 1 ] < n - 1 ) : NEW_LINE INDENT print ( " GEEKS β lost " , end = " β " ) NEW_LINE return NEW_LINE DEDENT if ( count [ 1 ] == n and count [ 0 ] < n - 1 ) : NEW_LINE INDENT print ( " GEEKS β won " , end = " β " ) NEW_LINE return NEW_LINE DEDENT if ( count [ 0 ] == n - 1 and count [ 1 ] == n - 1 ) : NEW_LINE INDENT count [ 0 ] = 0 NEW_LINE count [ 1 ] = 0 NEW_LINE break NEW_LINE DEDENT DEDENT i += 1 NEW_LINE for i in range ( i , len ( score ) , 1 ) : NEW_LINE INDENT index = ord ( score [ i ] ) - ord ( '0' ) NEW_LINE count [ index ] += 1 NEW_LINE if ( abs ( count [ 0 ] - count [ 1 ] ) == 2 ) : NEW_LINE INDENT if ( count [ 0 ] > count [ 1 ] ) : NEW_LINE INDENT print ( " GEEKS β lost " , end = " β " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " GEEKS β won " , end = " β " ) ; NEW_LINE DEDENT return NEW_LINE DEDENT DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT score = "1001010101111011101111" NEW_LINE n = 15 NEW_LINE predictWinner ( score , n ) NEW_LINE DEDENT |
Number of Counterclockwise shifts to make a string palindrome | Function to check if given string is palindrome or not . ; Function to find counter clockwise shifts to make string palindrome . ; Pointer to starting of current shifted string . ; Pointer to ending of current shifted string . ; Concatenate string with itself ; To store counterclockwise shifts ; Move left and right pointers one step at a time . ; Check if current shifted string is palindrome or not ; If string is not palindrome then increase count of number of shifts by 1. ; Driver code . | def isPalindrome ( str , l , r ) : NEW_LINE INDENT while ( l < r ) : NEW_LINE INDENT if ( str [ l ] != str [ r ] ) : NEW_LINE INDENT return False NEW_LINE DEDENT l += 1 NEW_LINE r -= 1 NEW_LINE DEDENT return True NEW_LINE DEDENT def CyclicShifts ( str ) : NEW_LINE INDENT n = len ( str ) NEW_LINE left = 0 NEW_LINE right = n - 1 NEW_LINE str = str + str NEW_LINE cnt = 0 NEW_LINE while ( right < 2 * n - 1 ) : NEW_LINE INDENT if ( isPalindrome ( str , left , right ) ) : NEW_LINE INDENT break NEW_LINE DEDENT cnt += 1 NEW_LINE left += 1 NEW_LINE right += 1 NEW_LINE DEDENT return cnt NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT str = " bccbbaab " ; NEW_LINE print ( CyclicShifts ( str ) ) NEW_LINE DEDENT |
Find a string such that every character is lexicographically greater than its immediate next character | Function that prints the required string ; Find modulus with 26 ; Print extra characters required ; Print the given reverse string countOfStr times ; Driver Code ; Initialize a string in reverse order | def printString ( n , str ) : NEW_LINE INDENT str2 = " " NEW_LINE extraChar = n % 26 NEW_LINE if ( extraChar >= 1 ) : NEW_LINE INDENT for i in range ( 26 - ( extraChar + 1 ) , 26 ) : NEW_LINE INDENT str2 += str [ i ] NEW_LINE DEDENT DEDENT countOfStr = n // 26 NEW_LINE for i in range ( 1 , countOfStr + 1 ) : NEW_LINE INDENT for j in range ( 26 ) : NEW_LINE INDENT str2 += str [ j ] NEW_LINE DEDENT DEDENT return str2 NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT n = 30 NEW_LINE str = " zyxwvutsrqponmlkjihgfedcba " NEW_LINE print ( printString ( n , str ) ) NEW_LINE DEDENT |
Longest Common Prefix Matching | Set | A Utility Function to find the common prefix between first and last strings ; Compare str1 and str2 ; A Function that returns the longest common prefix from the array of strings ; sorts the N set of strings ; prints the common prefix of the first and the last string of the set of strings ; Driver Code | def commonPrefixUtil ( str1 , str2 ) : NEW_LINE INDENT n1 = len ( str1 ) NEW_LINE n2 = len ( str2 ) NEW_LINE result = " " NEW_LINE j = 0 NEW_LINE i = 0 NEW_LINE while ( i <= n1 - 1 and j <= n2 - 1 ) : NEW_LINE INDENT if ( str1 [ i ] != str2 [ j ] ) : NEW_LINE INDENT break NEW_LINE DEDENT result += ( str1 [ i ] ) NEW_LINE i += 1 NEW_LINE j += 1 NEW_LINE DEDENT return ( result ) NEW_LINE DEDENT def commonPrefix ( arr , n ) : NEW_LINE INDENT arr . sort ( reverse = False ) NEW_LINE print ( commonPrefixUtil ( arr [ 0 ] , arr [ n - 1 ] ) ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ " geeksforgeeks " , " geeks " , " geek " , " geezer " ] NEW_LINE n = len ( arr ) NEW_LINE commonPrefix ( arr , n ) NEW_LINE DEDENT |
Square of large number represented as String | Multiplies str1 and str2 , and prints result . ; Will keep the result number in vector in reverse order ; Below two indexes are used to find positions in result . ; Go from right to left in num1 ; To shift position to left after every multiplication of a digit in num2 ; Go from right to left in num2 ; Take current digit of second number ; Multiply with current digit of first number and add result to previously stored result at current position . ; Carry for next iteration ; Store result ; Store carry in next cell ; To shift position to left after every multiplication of a digit in num1 . ; Ignore '0' s from the right ; If all were '0' s - means either both or one of num1 or num2 were '0 ; Generate the result string ; Driver code | def multiply ( num1 , num2 ) : NEW_LINE INDENT n1 = len ( num1 ) NEW_LINE n2 = len ( num2 ) NEW_LINE if ( n1 == 0 or n2 == 0 ) : NEW_LINE INDENT return "0" NEW_LINE DEDENT result = [ 0 ] * ( n1 + n2 ) NEW_LINE i_n1 = 0 NEW_LINE i_n2 = 0 NEW_LINE for i in range ( n1 - 1 , - 1 , - 1 ) : NEW_LINE INDENT carry = 0 NEW_LINE n_1 = ord ( num1 [ i ] ) - ord ( '0' ) NEW_LINE i_n2 = 0 NEW_LINE for j in range ( n2 - 1 , - 1 , - 1 ) : NEW_LINE INDENT n_2 = ord ( num2 [ j ] ) - ord ( '0' ) NEW_LINE sum = n_1 * n_2 + result [ i_n1 + i_n2 ] + carry NEW_LINE carry = sum // 10 NEW_LINE result [ i_n1 + i_n2 ] = sum % 10 NEW_LINE i_n2 += 1 NEW_LINE DEDENT if ( carry > 0 ) : NEW_LINE INDENT result [ i_n1 + i_n2 ] += carry NEW_LINE DEDENT i_n1 += 1 NEW_LINE DEDENT i = len ( result ) - 1 NEW_LINE while ( i >= 0 and result [ i ] == 0 ) : NEW_LINE INDENT i -= 1 NEW_LINE DEDENT DEDENT ' NEW_LINE INDENT if ( i == - 1 ) : NEW_LINE INDENT return "0" NEW_LINE DEDENT s = " " NEW_LINE while ( i >= 0 ) : NEW_LINE INDENT s += str ( result [ i ] ) NEW_LINE i -= 1 NEW_LINE DEDENT return s NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT str1 = "454545454545454545" NEW_LINE print ( multiply ( str1 , str1 ) ) NEW_LINE DEDENT |
Perform n steps to convert every digit of a number in the format [ count ] [ digit ] | Function to perform every step ; perform N steps ; Traverse in the string ; for last digit ; recur for current string ; Driver Code | def countDigits ( st , n ) : NEW_LINE INDENT if ( n > 0 ) : NEW_LINE INDENT cnt = 1 NEW_LINE i = 0 NEW_LINE st2 = " " NEW_LINE i = 1 NEW_LINE while ( i < len ( st ) ) : NEW_LINE INDENT if ( st [ i ] == st [ i - 1 ] ) : NEW_LINE INDENT cnt = cnt + 1 NEW_LINE DEDENT else : NEW_LINE INDENT st2 += chr ( 48 + cnt ) NEW_LINE st2 += st [ i - 1 ] NEW_LINE cnt = 1 NEW_LINE DEDENT i = i + 1 NEW_LINE DEDENT st2 += chr ( 48 + cnt ) NEW_LINE st2 += st [ i - 1 ] NEW_LINE countDigits ( st2 , n - 1 ) NEW_LINE n = n - 1 ; NEW_LINE DEDENT else : NEW_LINE INDENT print ( st ) NEW_LINE DEDENT DEDENT num = "123" NEW_LINE n = 3 NEW_LINE countDigits ( num , n ) NEW_LINE |
Sudo Placement | Special Subsequences | Python3 program to find all special subsequences of the given type ; Function to generate the required subsequences ; If the index pointer has reached the end of input string ; Skip empty ( " β " ) subsequence ; Exclude current character in output string ; Include current character in output string ; Remove the current included character and and include it in its uppercase form ; Function to print the required subsequences ; Output String to store every subsequence ; Set of strings that will store all special subsequences in lexicographical sorted order ; Sort the strings to print in sorted order ; Driver Code | from typing import List NEW_LINE def generateSubsequences ( input : str , output : str , idx : int , ans : List [ str ] ) -> None : NEW_LINE INDENT if idx == len ( input ) : NEW_LINE INDENT if ( len ( output ) ) : NEW_LINE INDENT ans . append ( output ) NEW_LINE DEDENT return NEW_LINE DEDENT generateSubsequences ( input , output , idx + 1 , ans ) NEW_LINE output += input [ idx ] NEW_LINE generateSubsequences ( input , output , idx + 1 , ans ) NEW_LINE output = output [ : - 1 ] NEW_LINE upper = input [ idx ] NEW_LINE upper = upper . upper ( ) NEW_LINE output += upper NEW_LINE generateSubsequences ( input , output , idx + 1 , ans ) NEW_LINE DEDENT def printSubsequences ( S : str ) -> None : NEW_LINE INDENT output = " " NEW_LINE ans = [ ] NEW_LINE generateSubsequences ( S , output , 0 , ans ) NEW_LINE ans . sort ( ) NEW_LINE for string in ans : NEW_LINE INDENT print ( string , end = " β " ) NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT S = " ab " NEW_LINE printSubsequences ( S ) NEW_LINE DEDENT |
Check if the given string of words can be formed from words present in the dictionary | Function to check if the word is in the dictionary or not ; map to store all words in dictionary with their count ; adding all words in map ; search in map for all words in the sentence ; all words of sentence are present ; Driver Code ; Calling function to check if words are present in the dictionary or not | def match_words ( dictionary , sentence , n , m ) : NEW_LINE INDENT mp = dict ( ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT mp [ dictionary [ i ] ] = mp . get ( dictionary [ i ] , 0 ) + 1 NEW_LINE DEDENT for i in range ( m ) : NEW_LINE INDENT if ( mp [ sentence [ i ] ] ) : NEW_LINE INDENT mp [ sentence [ i ] ] -= 1 NEW_LINE DEDENT else : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT return True NEW_LINE DEDENT dictionary = [ " find " , " a " , " geeks " , " all " , " for " , " on " , " geeks " , " answers " , " inter " ] NEW_LINE n = len ( dictionary ) NEW_LINE sentence = [ " find " , " all " , " answers " , " on " , " geeks " , " for " , " geeks " ] NEW_LINE m = len ( sentence ) NEW_LINE if ( match_words ( dictionary , sentence , n , m ) ) : NEW_LINE INDENT print ( " YES " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " NO " ) NEW_LINE DEDENT |
Print all 3 digit repeating numbers in a very large number | Function to print 3 digit repeating numbers ; Hashmap to store the frequency of a 3 digit number ; first three digit number ; if key already exists increase value by 1 ; Output the three digit numbers with frequency > 1 ; Driver Code ; Input string ; Calling Function | def printNum ( s ) : NEW_LINE INDENT i , j , val = 0 , 0 , 0 NEW_LINE mp = { } NEW_LINE val = ( ( ord ( s [ 0 ] ) - ord ( '0' ) ) * 100 + ( ord ( s [ 1 ] ) - ord ( '0' ) ) * 10 + ( ord ( s [ 2 ] ) - ord ( '0' ) ) ) NEW_LINE mp [ val ] = 1 NEW_LINE for i in range ( 3 , len ( s ) ) : NEW_LINE INDENT val = ( val % 100 ) * 10 + ord ( s [ i ] ) - ord ( '0' ) NEW_LINE if ( val in mp ) : NEW_LINE INDENT mp [ val ] = mp [ val ] + 1 NEW_LINE DEDENT else : NEW_LINE INDENT mp [ val ] = 1 NEW_LINE DEDENT DEDENT for m in mp : NEW_LINE INDENT key = m NEW_LINE value = mp [ m ] NEW_LINE if ( value > 1 ) : NEW_LINE INDENT print ( key , " β - β " , value , " β times " ) NEW_LINE DEDENT DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT input = "123412345123456" NEW_LINE printNum ( input ) NEW_LINE DEDENT |
Count occurrences of a substring recursively | Recursive function to count the number of occurrences of " hi " in str . ; Base Case ; Recursive Case Checking if the first substring matches ; Otherwise , return the count from the remaining index ; Driver Code | def countSubstrig ( str1 , str2 ) : NEW_LINE INDENT n1 = len ( str1 ) ; NEW_LINE n2 = len ( str2 ) ; NEW_LINE if ( n1 == 0 or n1 < n2 ) : NEW_LINE INDENT return 0 ; NEW_LINE DEDENT if ( str1 [ 0 : n2 ] == str2 ) : NEW_LINE INDENT return countSubstrig ( str1 [ n2 - 1 : ] , str2 ) + 1 ; NEW_LINE DEDENT return countSubstrig ( str1 [ n2 - 1 : ] , str2 ) ; NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT str1 = " geeksforgeeks " ; NEW_LINE str2 = " geeks " ; NEW_LINE print ( countSubstrig ( str1 , str2 ) ) ; NEW_LINE str1 = " hikakashi " ; NEW_LINE str2 = " hi " ; NEW_LINE print ( countSubstrig ( str1 , str2 ) ) ; NEW_LINE DEDENT |
Check if a binary string contains all permutations of length k | Python3 Program to Check If a String Contains All Binary Codes of Size K ; Unordered map of type string ; Driver code | def hasAllcodes ( s , k ) : NEW_LINE INDENT us = set ( ) NEW_LINE for i in range ( len ( s ) + 1 ) : NEW_LINE INDENT us . add ( s [ i : k ] ) NEW_LINE DEDENT return len ( us ) == 1 << k NEW_LINE DEDENT s = "00110110" NEW_LINE k = 2 NEW_LINE if ( hasAllcodes ) : NEW_LINE INDENT print ( " YES " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " NO " ) NEW_LINE DEDENT |
Add n binary strings | This function adds two binary strings and return result as a third string ; Initialize result ; Initialize digit sum ; Traverse both strings starting from last characters ; Compute sum of last digits and carry ; If current digit sum is 1 or 3 , add 1 to result ; Compute carry ; Move to next digits ; function to add n binary strings ; Driver code | def addBinaryUtil ( a , b ) : NEW_LINE result = " " ; NEW_LINE s = 0 ; NEW_LINE INDENT i = len ( a ) - 1 ; NEW_LINE j = len ( b ) - 1 ; NEW_LINE while ( i >= 0 or j >= 0 or s == 1 ) : NEW_LINE INDENT s += ( ord ( a [ i ] ) - ord ( '0' ) ) if ( i >= 0 ) else 0 ; NEW_LINE s += ( ord ( b [ j ] ) - ord ( '0' ) ) if ( j >= 0 ) else 0 ; NEW_LINE result = chr ( s % 2 + ord ( '0' ) ) + result ; NEW_LINE s //= 2 ; NEW_LINE i -= 1 ; NEW_LINE j -= 1 ; NEW_LINE DEDENT return result ; NEW_LINE DEDENT def addBinary ( arr , n ) : NEW_LINE INDENT result = " " ; NEW_LINE for i in range ( n ) : NEW_LINE INDENT result = addBinaryUtil ( result , arr [ i ] ) ; NEW_LINE DEDENT return result ; NEW_LINE DEDENT arr = [ "1" , "10" , "11" ] ; NEW_LINE n = len ( arr ) ; NEW_LINE print ( addBinary ( arr , n ) ) ; NEW_LINE |
Reverse String according to the number of words | Reverse the letters of the word ; Temporary variable to store character ; Swapping the first and last character ; This function forms the required string ; Checking the number of words present in string to reverse ; Reverse the letter of the words ; Driver Code | def reverse ( string , start , end ) : NEW_LINE INDENT temp = ' ' NEW_LINE while start <= end : NEW_LINE INDENT temp = string [ start ] NEW_LINE string [ start ] = string [ end ] NEW_LINE string [ end ] = temp NEW_LINE start += 1 NEW_LINE end -= 1 NEW_LINE DEDENT DEDENT def reverseletter ( string , start , end ) : NEW_LINE INDENT wstart , wend = start , start NEW_LINE while wend < end : NEW_LINE INDENT if string [ wend ] == " β " : NEW_LINE INDENT wend += 1 NEW_LINE continue NEW_LINE DEDENT while wend <= end and string [ wend ] != " β " : NEW_LINE INDENT wend += 1 NEW_LINE DEDENT wend -= 1 NEW_LINE reverse ( string , wstart , wend ) NEW_LINE wend += 1 NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT string = " Ashish β Yadav β Abhishek β Rajput β Sunil β Pundir " NEW_LINE string = list ( string ) NEW_LINE reverseletter ( string , 0 , len ( string ) - 1 ) NEW_LINE print ( ' ' . join ( string ) ) NEW_LINE DEDENT |
Minimum bit changes in Binary Circular array to reach a index | finding which path have minimum flip bit and the minimum flip bits ; concatenating given string to itself , to make it circular ; check x is greater than y . marking if output need to be opposite . ; iterate Clockwise ; if current bit is not equal to next index bit . ; iterate Anti - Clockwise ; if current bit is not equal to next index bit . ; Finding whether Clockwise or Anti - clockwise path take minimum flip . ; Driver Code | def minimumFlip ( s , x , y ) : NEW_LINE INDENT s = s + s NEW_LINE isOpposite = False NEW_LINE if ( x > y ) : NEW_LINE INDENT temp = y NEW_LINE y = x ; NEW_LINE x = temp NEW_LINE isOpposite = True NEW_LINE DEDENT valClockwise = 0 NEW_LINE cur = s [ x ] NEW_LINE for i in range ( x , y + 1 , 1 ) : NEW_LINE INDENT if ( s [ i ] != cur ) : NEW_LINE INDENT cur = s [ i ] NEW_LINE valClockwise += 1 NEW_LINE DEDENT DEDENT valAnticlockwise = 0 NEW_LINE cur = s [ y ] NEW_LINE x += len ( s ) - 1 NEW_LINE for i in range ( y , x + 1 , 1 ) : NEW_LINE INDENT if ( s [ i ] != cur ) : NEW_LINE INDENT cur = s [ i ] NEW_LINE valAnticlockwise += 1 NEW_LINE DEDENT DEDENT if ( valClockwise <= valAnticlockwise ) : NEW_LINE INDENT if ( isOpposite == False ) : NEW_LINE INDENT print ( " Clockwise " , valClockwise ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " Anti - clockwise " , valAnticlockwise ) NEW_LINE DEDENT DEDENT else : NEW_LINE INDENT if ( isOpposite == False ) : NEW_LINE INDENT print ( " Anti - clockwise " , valAnticlockwise ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " Clockwise " , valClockwise ) NEW_LINE DEDENT DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT x = 0 NEW_LINE y = 8 NEW_LINE s = "000110" NEW_LINE minimumFlip ( s , x , y ) NEW_LINE DEDENT |
Prefixes with more a than b | Function to count prefixes ; calculating for string S ; count == 0 or when N == 1 ; when all characters are a or a - b == 0 ; checking for saturation of string after repetitive addition ; Driver Code | def prefix ( k , n ) : NEW_LINE INDENT a = 0 NEW_LINE b = 0 NEW_LINE count = 0 NEW_LINE i = 0 NEW_LINE Len = len ( k ) NEW_LINE for i in range ( Len ) : NEW_LINE INDENT if ( k [ i ] == " a " ) : NEW_LINE INDENT a += 1 NEW_LINE DEDENT if ( k [ i ] == " b " ) : NEW_LINE INDENT b += 1 NEW_LINE DEDENT if ( a > b ) : NEW_LINE INDENT count += 1 NEW_LINE DEDENT DEDENT if ( count == 0 or n == 1 ) : NEW_LINE INDENT print ( count ) NEW_LINE return 0 NEW_LINE DEDENT if ( count == Len or a - b == 0 ) : NEW_LINE INDENT print ( count * n ) NEW_LINE return 0 NEW_LINE DEDENT n2 = n - 1 NEW_LINE count2 = 0 NEW_LINE while ( n2 != 0 ) : NEW_LINE INDENT for i in range ( Len ) : NEW_LINE INDENT if ( k [ i ] == " a " ) : NEW_LINE INDENT a += 1 NEW_LINE DEDENT if ( k [ i ] == " b " ) : NEW_LINE INDENT b += 1 NEW_LINE DEDENT if ( a > b ) : NEW_LINE INDENT count2 += 1 NEW_LINE DEDENT DEDENT count += count2 NEW_LINE n2 -= 1 NEW_LINE if ( count2 == 0 ) : NEW_LINE INDENT break NEW_LINE DEDENT if ( count2 == Len ) : NEW_LINE INDENT count += ( n2 * count2 ) NEW_LINE break NEW_LINE DEDENT count2 = 0 NEW_LINE DEDENT return count NEW_LINE DEDENT S = " aba " NEW_LINE N = 2 NEW_LINE print ( prefix ( S , N ) ) NEW_LINE S = " baa " NEW_LINE N = 3 NEW_LINE print ( prefix ( S , N ) ) NEW_LINE |
Pairs whose concatenation contain all digits | Python3 Program to find number of pairs whose concatenation contains all digits from 0 to 9. ; Function to return number of pairs whose concatenation contain all digits from 0 to 9 ; Making the mask for each of the number . ; for each of the possible pair which can make OR value equal to 1023 ; Finding the count of pair from the given numbers . ; Driven Program | N = 20 NEW_LINE def countPair ( st , n ) : NEW_LINE INDENT cnt = [ 0 ] * ( 1 << 10 ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT mask = 0 NEW_LINE for j in range ( len ( st [ i ] ) ) : NEW_LINE INDENT mask |= ( 1 << ( ord ( st [ i ] [ j ] ) - ord ( '0' ) ) ) NEW_LINE DEDENT cnt [ mask ] += 1 NEW_LINE DEDENT ans = 0 NEW_LINE for m1 in range ( 1024 ) : NEW_LINE INDENT for m2 in range ( 1024 ) : NEW_LINE INDENT if ( ( m1 m2 ) == 1023 ) : NEW_LINE INDENT if ( m1 == m2 ) : NEW_LINE INDENT ans += ( cnt [ m1 ] * ( cnt [ m1 ] - 1 ) ) NEW_LINE DEDENT else : NEW_LINE INDENT ans += ( cnt [ m1 ] * cnt [ m2 ] ) NEW_LINE DEDENT DEDENT DEDENT DEDENT return ans // 2 NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT n = 5 NEW_LINE st = [ "129300455" , "5559948277" , "012334556" , "56789" , "123456879" ] NEW_LINE print ( countPair ( st , n ) ) NEW_LINE DEDENT |
Count binary strings with twice zeros in first half | pre define some constant ; global values for pre computation ; function to print number of required string ; calculate answer using proposed algorithm ; Driver code | mod = 1000000007 NEW_LINE Max = 1001 NEW_LINE nCr = [ [ 0 for _ in range ( 1003 ) ] for i in range ( 1003 ) ] NEW_LINE def preComputeCoeff ( ) : NEW_LINE INDENT for i in range ( Max ) : NEW_LINE INDENT for j in range ( i + 1 ) : NEW_LINE INDENT if ( j == 0 or j == i ) : NEW_LINE INDENT nCr [ i ] [ j ] = 1 NEW_LINE DEDENT else : NEW_LINE INDENT nCr [ i ] [ j ] = ( nCr [ i - 1 ] [ j - 1 ] + nCr [ i - 1 ] [ j ] ) % mod NEW_LINE DEDENT DEDENT DEDENT DEDENT def computeStringCount ( N ) : NEW_LINE INDENT n = N // 2 NEW_LINE ans = 0 NEW_LINE for i in range ( 2 , n + 1 , 2 ) : NEW_LINE INDENT ans = ( ans + ( ( nCr [ n ] [ i ] * nCr [ n ] [ i // 2 ] ) % mod ) ) % mod NEW_LINE DEDENT return ans NEW_LINE DEDENT preComputeCoeff ( ) NEW_LINE N = 3 NEW_LINE print ( computeStringCount ( N ) ) NEW_LINE |
Count of ' GFG ' Subsequences in the given string | Python 3 Program to find the " GFG " subsequence in the given string ; Print the count of " GFG " subsequence in the string ; Traversing the given string ; If the character is ' G ' , increment the count of ' G ' , increase the result and update the array . ; If the character is ' F ' , increment the count of ' F ' and update the array . ; Ignore other character . ; Driver Code | MAX = 100 NEW_LINE def countSubsequence ( s , n ) : NEW_LINE INDENT cntG = 0 NEW_LINE cntF = 0 NEW_LINE result = 0 NEW_LINE C = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( s [ i ] == ' G ' ) : NEW_LINE INDENT cntG += 1 NEW_LINE result += C NEW_LINE continue NEW_LINE DEDENT if ( s [ i ] == ' F ' ) : NEW_LINE INDENT cntF += 1 NEW_LINE C += cntG NEW_LINE continue NEW_LINE DEDENT else : NEW_LINE INDENT continue NEW_LINE DEDENT DEDENT print ( result ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT s = " GFGFG " NEW_LINE n = len ( s ) NEW_LINE countSubsequence ( s , n ) NEW_LINE DEDENT |
Lexicographical Maximum substring of string | Python 3 program to find the lexicographically maximum substring . ; loop to find the max leicographic substring in the substring array ; Driver code | def LexicographicalMaxString ( str ) : NEW_LINE INDENT mx = " " NEW_LINE for i in range ( len ( str ) ) : NEW_LINE INDENT mx = max ( mx , str [ i : ] ) NEW_LINE DEDENT return mx NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT str = " ababaa " NEW_LINE print ( LexicographicalMaxString ( str ) ) NEW_LINE DEDENT |
Lexicographical Maximum substring of string | Python 3 program to find the lexicographically maximum substring . ; We store all the indexes of maximum characters we have in the string ; We form a substring from that maximum character index till end and check if its greater that maxstring ; Driver code | def LexicographicalMaxString ( st ) : NEW_LINE INDENT maxchar = ' a ' NEW_LINE index = [ ] NEW_LINE for i in range ( len ( st ) ) : NEW_LINE INDENT if ( st [ i ] >= maxchar ) : NEW_LINE INDENT maxchar = st [ i ] NEW_LINE index . append ( i ) NEW_LINE DEDENT DEDENT maxstring = " " NEW_LINE for i in range ( len ( index ) ) : NEW_LINE INDENT if ( st [ index [ i ] : len ( st ) ] > maxstring ) : NEW_LINE INDENT maxstring = st [ index [ i ] : len ( st ) ] NEW_LINE DEDENT DEDENT return maxstring NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT st = " acbacbc " NEW_LINE print ( LexicographicalMaxString ( st ) ) NEW_LINE DEDENT |
Print longest palindrome word in a sentence | Function to check if a word is palindrome ; making the check case case insensitive ; loop to check palindrome ; Function to find longest palindrome word ; to check last word for palindrome ; to store each word ; extracting each word ; Driver code | def checkPalin ( word ) : NEW_LINE INDENT n = len ( word ) NEW_LINE word = word . lower ( ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( word [ i ] != word [ n - 1 ] ) : NEW_LINE INDENT return False NEW_LINE DEDENT n -= 1 NEW_LINE DEDENT return True NEW_LINE DEDENT def longestPalin ( str ) : NEW_LINE INDENT str = str + " β " NEW_LINE longestword = " " NEW_LINE word = " " NEW_LINE length1 = 0 NEW_LINE for i in range ( len ( str ) ) : NEW_LINE INDENT ch = str [ i ] NEW_LINE if ( ch != ' β ' ) : NEW_LINE INDENT word = word + ch NEW_LINE DEDENT else : NEW_LINE INDENT length = len ( word ) NEW_LINE if ( checkPalin ( word ) and length > length1 ) : NEW_LINE INDENT length1 = length NEW_LINE longestword = word NEW_LINE DEDENT word = " " NEW_LINE DEDENT DEDENT return longestword NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT s = " My β name β is β ava β and β i β love β Geeksforgeeks " NEW_LINE if ( longestPalin ( s ) == " " ) : NEW_LINE INDENT print ( " No β Palindrome β Word " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( longestPalin ( s ) ) NEW_LINE DEDENT DEDENT |
Number of common base strings for two strings | function for finding common divisor . ; Checking if ' base ' is base string of 's1 ; Checking if ' base ' is base string of 's2 ; Driver code | def isCommonBase ( base , s1 , s2 ) : NEW_LINE ' NEW_LINE INDENT for j in range ( len ( s1 ) ) : NEW_LINE INDENT if ( base [ j % len ( base ) ] != s1 [ j ] ) : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT DEDENT ' NEW_LINE INDENT for j in range ( len ( s2 ) ) : NEW_LINE INDENT if ( base [ j % len ( base ) ] != s2 [ j ] ) : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT return True NEW_LINE DEDENT def countCommonBases ( s1 , s2 ) : NEW_LINE INDENT n1 = len ( s1 ) NEW_LINE n2 = len ( s2 ) NEW_LINE count = 0 NEW_LINE for i in range ( 1 , min ( n1 , n2 ) + 1 ) : NEW_LINE INDENT base = s1 [ 0 : i ] NEW_LINE if ( isCommonBase ( base , s1 , s2 ) ) : NEW_LINE INDENT count += 1 NEW_LINE DEDENT DEDENT return count NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT s1 = " pqrspqrs " NEW_LINE s2 = " pqrspqrspqrspqrs " NEW_LINE print ( countCommonBases ( s1 , s2 ) ) NEW_LINE DEDENT |
Removing elements between the two zeros | Function to find the string after operation ; Travesing through string ; Checking for character Between two zeros ; Deleting the character At specific position ; Updating the length of the string ; Driver code | def findstring ( s ) : NEW_LINE INDENT n = len ( s ) NEW_LINE s = list ( s ) NEW_LINE i = 1 NEW_LINE while i < n - 1 : NEW_LINE INDENT if ( s [ i - 1 ] == '0' and s [ i + 1 ] == '0' ) : NEW_LINE INDENT s . pop ( i ) NEW_LINE i -= 1 NEW_LINE if i > 0 and s [ i - 1 ] == '0' : NEW_LINE INDENT i -= 1 NEW_LINE DEDENT n = len ( s ) NEW_LINE DEDENT i += 1 NEW_LINE DEDENT return ' ' . join ( s ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT print ( findstring ( '100100' ) ) NEW_LINE DEDENT |
Perfect Square String | Python3 program to find if string is a perfect square or not . ; calculating the length of the string ; calculating the ASCII value of the string ; Find floating point value of square root of x . ; If square root is an integer ; Driver code | import math ; NEW_LINE def isPerfectSquareString ( str ) : NEW_LINE INDENT sum = 0 ; NEW_LINE l = len ( str ) ; NEW_LINE for i in range ( l ) : NEW_LINE INDENT sum = sum + ord ( str [ i ] ) ; NEW_LINE DEDENT squareRoot = math . sqrt ( sum ) ; NEW_LINE return ( ( squareRoot - math . floor ( squareRoot ) ) == 0 ) ; NEW_LINE DEDENT str = " d " ; NEW_LINE if ( isPerfectSquareString ( str ) ) : NEW_LINE INDENT print ( " Yes " ) ; NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) ; NEW_LINE DEDENT |
Remove consecutive vowels from string | function which returns True or False for occurrence of a vowel ; this compares vowel with character 'c ; function to print resultant string ; print 1 st character ; loop to check for each character ; comparison of consecutive characters ; Driver code | def is_vow ( c ) : NEW_LINE ' NEW_LINE INDENT return ( ( c == ' a ' ) or ( c == ' e ' ) or ( c == ' i ' ) or ( c == ' o ' ) or ( c == ' u ' ) ) ; NEW_LINE DEDENT def removeVowels ( str ) : NEW_LINE INDENT print ( str [ 0 ] , end = " " ) ; NEW_LINE for i in range ( 1 , len ( str ) ) : NEW_LINE INDENT if ( ( is_vow ( str [ i - 1 ] ) != True ) or ( is_vow ( str [ i ] ) != True ) ) : NEW_LINE INDENT print ( str [ i ] , end = " " ) ; NEW_LINE DEDENT DEDENT DEDENT str = " β geeks β for β geeks " ; NEW_LINE removeVowels ( str ) ; NEW_LINE |
Find the Number which contain the digit d | Python 3 program to print the number which contain the digit d from 0 to n ; function to display the values ; Converting d to character ; Loop to check each digit one by one . ; initialize the string ; checking for digit ; Driver code | def index ( st , ch ) : NEW_LINE INDENT for i in range ( len ( st ) ) : NEW_LINE INDENT if ( st [ i ] == ch ) : NEW_LINE INDENT return i ; NEW_LINE DEDENT DEDENT return - 1 NEW_LINE DEDENT def printNumbers ( n , d ) : NEW_LINE INDENT st = " " + str ( d ) NEW_LINE ch = st [ 0 ] NEW_LINE for i in range ( 0 , n + 1 , 1 ) : NEW_LINE INDENT st = " " NEW_LINE st = st + str ( i ) NEW_LINE if ( i == d or index ( st , ch ) >= 0 ) : NEW_LINE INDENT print ( i , end = " β " ) NEW_LINE DEDENT DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT n = 100 NEW_LINE d = 5 NEW_LINE printNumbers ( n , d ) NEW_LINE DEDENT |
Transform a string such that it has abcd . . z as a subsequence | function to transform string with string passed as reference ; initializing the variable ch to 'a ; if the length of string is less than 26 , we can 't obtain the required subsequence ; if ch has reached ' z ' , it means we have transformed our string such that required subsequence can be obtained ; current character is not greater than ch , then replace it with ch and increment ch ; Driver Code | def transformString ( s ) : NEW_LINE ' NEW_LINE INDENT ch = ' a ' NEW_LINE if ( len ( s ) < 26 ) : NEW_LINE INDENT return False NEW_LINE DEDENT for i in range ( 0 , len ( s ) ) : NEW_LINE INDENT if ( ord ( ch ) > ord ( ' z ' ) ) : NEW_LINE INDENT break NEW_LINE DEDENT if ( s [ i ] <= ch ) : NEW_LINE INDENT s [ i ] = ch NEW_LINE ch = chr ( ord ( ch ) + 1 ) NEW_LINE DEDENT DEDENT if ( ch <= ' z ' ) : NEW_LINE INDENT print ( " Not β Possible " ) NEW_LINE DEDENT print ( " " . join ( s ) ) NEW_LINE DEDENT s = list ( " aaaaaaaaaaaaaaaaaaaaaaaaaa " ) NEW_LINE transformString ( s ) NEW_LINE |
Number of pairs with Pandigital Concatenation | Checks if a given is Pandigital ; digit i is not present thus not pandigital ; Returns number of pairs of strings resulting in Pandigital Concatenations ; iterate over all pair of strings ; Driver code | def isPanDigital ( s ) : NEW_LINE INDENT digits = [ False ] * 10 ; NEW_LINE for i in range ( 0 , len ( s ) ) : NEW_LINE INDENT digits [ int ( s [ i ] ) - int ( '0' ) ] = True NEW_LINE DEDENT for i in range ( 0 , 10 ) : NEW_LINE INDENT if ( digits [ i ] == False ) : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT return True NEW_LINE DEDENT def countPandigitalPairs ( v ) : NEW_LINE INDENT pairs = 0 NEW_LINE for i in range ( 0 , len ( v ) ) : NEW_LINE INDENT for j in range ( i + 1 , len ( v ) ) : NEW_LINE INDENT if ( isPanDigital ( v [ i ] + v [ j ] ) ) : NEW_LINE INDENT pairs = pairs + 1 NEW_LINE DEDENT DEDENT DEDENT return pairs NEW_LINE DEDENT v = [ "123567" , "098234" , "14765" , "19804" ] NEW_LINE print ( countPandigitalPairs ( v ) ) NEW_LINE |
Minimum changes to a string to make all substrings distinct | Python3 program to count number of changes to make all substrings distinct . ; Returns minimum changes to str so that no substring is repeated . ; If length is more than maximum allowed characters , we cannot get the required string . ; Variable to store count of distinct characters ; To store counts of different characters ; Answer is , n - number of distinct char ; Driver Code | MAX_CHAR = [ 26 ] NEW_LINE def minChanges ( str ) : NEW_LINE INDENT n = len ( str ) NEW_LINE if ( n > MAX_CHAR [ 0 ] ) : NEW_LINE INDENT return - 1 NEW_LINE DEDENT dist_count = 0 NEW_LINE count = [ 0 ] * MAX_CHAR [ 0 ] NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( count [ ord ( str [ i ] ) - ord ( ' a ' ) ] == 0 ) : NEW_LINE INDENT dist_count += 1 NEW_LINE DEDENT count [ ( ord ( str [ i ] ) - ord ( ' a ' ) ) ] += 1 NEW_LINE DEDENT return ( n - dist_count ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT str = " aebaecedabbee " NEW_LINE print ( minChanges ( str ) ) NEW_LINE DEDENT |
Reverse each word in a linked list node | Node of a linked list ; Function to create newNode in a linked list ; reverse each node data ; iterate each node and call reverse_word for each node data ; printing linked list ; Driver program | class Node : NEW_LINE INDENT def __init__ ( self , next = None , data = None ) : NEW_LINE INDENT self . next = next NEW_LINE self . data = data NEW_LINE DEDENT DEDENT def newNode ( c ) : NEW_LINE INDENT temp = Node ( ) NEW_LINE temp . c = c NEW_LINE temp . next = None NEW_LINE return temp NEW_LINE DEDENT def reverse_word ( str ) : NEW_LINE INDENT s = " " NEW_LINE i = 0 NEW_LINE while ( i < len ( str ) ) : NEW_LINE INDENT s = str [ i ] + s NEW_LINE i = i + 1 NEW_LINE DEDENT return s NEW_LINE DEDENT def reverse ( head ) : NEW_LINE INDENT ptr = head NEW_LINE while ( ptr != None ) : NEW_LINE INDENT ptr . c = reverse_word ( ptr . c ) NEW_LINE ptr = ptr . next NEW_LINE DEDENT return head NEW_LINE DEDENT def printList ( head ) : NEW_LINE INDENT while ( head != None ) : NEW_LINE INDENT print ( head . c , end = " β " ) NEW_LINE head = head . next NEW_LINE DEDENT DEDENT head = newNode ( " Geeksforgeeks " ) NEW_LINE head . next = newNode ( " a " ) NEW_LINE head . next . next = newNode ( " computer " ) NEW_LINE head . next . next . next = newNode ( " science " ) NEW_LINE head . next . next . next . next = newNode ( " portal " ) NEW_LINE head . next . next . next . next . next = newNode ( " for " ) NEW_LINE head . next . next . next . next . next . next = newNode ( " geeks " ) NEW_LINE print ( " List β before β reverse : β " ) NEW_LINE printList ( head ) NEW_LINE head = reverse ( head ) NEW_LINE print ( " List after reverse : " ) NEW_LINE printList ( head ) NEW_LINE |
Number of strings of length N with no palindromic sub string | Return the count of strings with no palindromic substring . ; Driven Program | def numofstring ( n , m ) : NEW_LINE INDENT if n == 1 : NEW_LINE INDENT return m NEW_LINE DEDENT if n == 2 : NEW_LINE INDENT return m * ( m - 1 ) NEW_LINE DEDENT return m * ( m - 1 ) * pow ( m - 2 , n - 2 ) NEW_LINE DEDENT n = 2 NEW_LINE m = 3 NEW_LINE print ( numofstring ( n , m ) ) NEW_LINE |
Count special palindromes in a String | Function to count special Palindromic susbstring ; store count of special Palindromic substring ; it will store the count of continues same char ; traverse string character from left to right ; store same character count ; count smiler character ; Case : 1 so total number of substring that we can generate are : K * ( K + 1 ) / 2 here K is sameCharCount ; store current same char count in sameChar [ ] array ; increment i ; Case 2 : Count all odd length Special Palindromic substring ; if current character is equal to previous one then we assign Previous same character count to current one ; case 2 : odd length ; subtract all single length substring ; Driver Code | def CountSpecialPalindrome ( str ) : NEW_LINE INDENT n = len ( str ) ; NEW_LINE result = 0 ; NEW_LINE sameChar = [ 0 ] * n ; NEW_LINE i = 0 ; NEW_LINE while ( i < n ) : NEW_LINE INDENT sameCharCount = 1 ; NEW_LINE j = i + 1 ; NEW_LINE while ( j < n ) : NEW_LINE INDENT if ( str [ i ] != str [ j ] ) : NEW_LINE INDENT break ; NEW_LINE DEDENT sameCharCount += 1 ; NEW_LINE j += 1 ; NEW_LINE DEDENT result += int ( sameCharCount * ( sameCharCount + 1 ) / 2 ) ; NEW_LINE sameChar [ i ] = sameCharCount ; NEW_LINE i = j ; NEW_LINE DEDENT for j in range ( 1 , n ) : NEW_LINE INDENT if ( str [ j ] == str [ j - 1 ] ) : NEW_LINE INDENT sameChar [ j ] = sameChar [ j - 1 ] ; NEW_LINE DEDENT if ( j > 0 and j < ( n - 1 ) and ( str [ j - 1 ] == str [ j + 1 ] and str [ j ] != str [ j - 1 ] ) ) : NEW_LINE INDENT result += ( sameChar [ j - 1 ] if ( sameChar [ j - 1 ] < sameChar [ j + 1 ] ) else sameChar [ j + 1 ] ) ; NEW_LINE DEDENT DEDENT return result - n ; NEW_LINE DEDENT str = " abccba " ; NEW_LINE print ( CountSpecialPalindrome ( str ) ) ; NEW_LINE |
Find if a string starts and ends with another given string | Python program to find if a given corner string is present at corners . ; If length of corner string is more , it cannot be present at corners . ; Return true if corner string is present at both corners of given string . ; Driver Code | def isCornerPresent ( str , corner ) : NEW_LINE INDENT n = len ( str ) NEW_LINE cl = len ( corner ) NEW_LINE if ( n < cl ) : NEW_LINE INDENT return False NEW_LINE DEDENT return ( ( str [ : cl ] == corner ) and ( str [ n - cl : ] == corner ) ) NEW_LINE DEDENT str = " geeksforgeeks " NEW_LINE corner = " geeks " NEW_LINE if ( isCornerPresent ( str , corner ) ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT |
Find i 'th Index character in a binary string obtained after n iterations | Function to store binary Representation ; Function to find ith character ; Function to change decimal to binary ; Assign s1 string in s string ; Driver code | def binary_conversion ( s , m ) : NEW_LINE INDENT while ( m ) : NEW_LINE INDENT temp = m % 2 NEW_LINE s += str ( temp ) NEW_LINE m = m // 2 NEW_LINE DEDENT return s [ : : - 1 ] NEW_LINE DEDENT def find_character ( n , m , i ) : NEW_LINE INDENT s = " " NEW_LINE s = binary_conversion ( s , m ) NEW_LINE s1 = " " NEW_LINE for x in range ( n ) : NEW_LINE INDENT for j in range ( len ( s ) ) : NEW_LINE INDENT if s [ j ] == "1" : NEW_LINE INDENT s1 += "10" NEW_LINE DEDENT else : NEW_LINE INDENT s1 += "01" NEW_LINE DEDENT DEDENT s = s1 NEW_LINE s1 = " " NEW_LINE DEDENT e = ord ( s [ i ] ) NEW_LINE r = ord ( '0' ) NEW_LINE return e - r NEW_LINE DEDENT m , n , i = 5 , 2 , 8 NEW_LINE print ( find_character ( n , m , i ) ) NEW_LINE |
Maximum segment value after putting k breakpoints in a number | Function to Find Maximum Number ; Maximum segment length ; Find value of first segment of seg_len ; Find value of remaining segments using sliding window ; To find value of current segment , first remove leading digit from previous value ; Then add trailing digit ; Driver Code | def findMaxSegment ( s , k ) : NEW_LINE INDENT seg_len = len ( s ) - k NEW_LINE res = 0 NEW_LINE for i in range ( seg_len ) : NEW_LINE INDENT res = res * 10 + ( ord ( s [ i ] ) - ord ( '0' ) ) NEW_LINE DEDENT seg_len_pow = pow ( 10 , seg_len - 1 ) NEW_LINE curr_val = res NEW_LINE for i in range ( 1 , len ( s ) - seg_len ) : NEW_LINE INDENT curr_val = curr_val - ( ord ( s [ i - 1 ] ) - ord ( '0' ) ) * seg_len_pow NEW_LINE curr_val = ( curr_val * 10 + ( ord ( s [ i + seg_len - 1 ] ) - ord ( '0' ) ) ) NEW_LINE res = max ( res , curr_val ) NEW_LINE DEDENT return res NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT s = "8754" NEW_LINE k = 2 NEW_LINE print ( " Maximum β number β = β " , findMaxSegment ( s , k ) ) NEW_LINE DEDENT |
Converting one string to other using append and delete last operations | Returns true if it is possible to convert str1 to str2 using k operations . ; Case A ( i ) ; finding common length of both string ; Case A ( ii ) - ; Case B - ; Driver Code | def isConvertible ( str1 , str2 , k ) : NEW_LINE INDENT if ( ( len ( str1 ) + len ( str2 ) ) < k ) : NEW_LINE INDENT return True NEW_LINE DEDENT commonLength = 0 NEW_LINE for i in range ( 0 , min ( len ( str1 ) , len ( str2 ) ) , 1 ) : NEW_LINE INDENT if ( str1 [ i ] == str2 [ i ] ) : NEW_LINE INDENT commonLength += 1 NEW_LINE DEDENT else : NEW_LINE INDENT break NEW_LINE DEDENT DEDENT if ( ( k - len ( str1 ) - len ( str2 ) + 2 * commonLength ) % 2 == 0 ) : NEW_LINE INDENT return True NEW_LINE DEDENT return False NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT str1 = " geek " NEW_LINE str2 = " geek " NEW_LINE k = 7 NEW_LINE if ( isConvertible ( str1 , str2 , k ) ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT str1 = " geeks " NEW_LINE str2 = " geek " NEW_LINE k = 5 NEW_LINE if ( isConvertible ( str1 , str2 , k ) ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT DEDENT |
Maximum distinct lowercase alphabets between two uppercase | Python3 Program to find maximum lowercase alphabets present between two uppercase alphabets ; Function which computes the maximum number of distinct lowercase alphabets between two uppercase alphabets ; Ignoring lowercase characters in the beginning . ; We start from next of first capital letter and traverse through remaining character . ; If character is in uppercase , ; Count all distinct lower case characters ; Update maximum count ; Reset count array ; If character is in lowercase ; Driver function | MAX_CHAR = 26 NEW_LINE def maxLower ( str ) : NEW_LINE INDENT n = len ( str ) NEW_LINE i = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT if str [ i ] >= ' A ' and str [ i ] <= ' Z ' : NEW_LINE INDENT i += 1 NEW_LINE break NEW_LINE DEDENT DEDENT maxCount = 0 NEW_LINE count = [ ] NEW_LINE for j in range ( MAX_CHAR ) : NEW_LINE INDENT count . append ( 0 ) NEW_LINE DEDENT for j in range ( i , n ) : NEW_LINE INDENT if str [ j ] >= ' A ' and str [ j ] <= ' Z ' : NEW_LINE INDENT currCount = 0 NEW_LINE for k in range ( MAX_CHAR ) : NEW_LINE INDENT if count [ k ] > 0 : NEW_LINE INDENT currCount += 1 NEW_LINE DEDENT DEDENT maxCount = max ( maxCount , currCount ) NEW_LINE for y in count : NEW_LINE INDENT y = 0 NEW_LINE DEDENT DEDENT if str [ j ] >= ' a ' and str [ j ] <= ' z ' : NEW_LINE INDENT count [ ord ( str [ j ] ) - ord ( ' a ' ) ] += 1 NEW_LINE DEDENT DEDENT return maxCount NEW_LINE DEDENT str = " zACaAbbaazzC " ; NEW_LINE print ( maxLower ( str ) ) NEW_LINE |
Maximum distinct lowercase alphabets between two uppercase | Function which computes the maximum number of distinct lowercase alphabets between two uppercase alphabets ; Ignoring lowercase characters in the beginning . ; We start from next of first capital letter and traverse through remaining character . ; If character is in uppercase , ; Update maximum count if lowercase character before this is more . ; clear the set ; If character is in lowercase ; Driver Code | def maxLower ( str ) : NEW_LINE INDENT n = len ( str ) ; NEW_LINE i = 0 ; NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( str [ i ] >= ' A ' and str [ i ] <= ' Z ' ) : NEW_LINE INDENT i += 1 ; NEW_LINE break ; NEW_LINE DEDENT DEDENT maxCount = 3 ; NEW_LINE s = set ( ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( str [ i ] >= ' A ' and str [ i ] <= ' Z ' ) : NEW_LINE INDENT maxCount = max ( maxCount , len ( s ) ) ; NEW_LINE s . clear ( ) ; NEW_LINE DEDENT if ( str [ i ] >= ' a ' and str [ i ] <= ' z ' ) : NEW_LINE INDENT s . add ( str [ i ] ) ; NEW_LINE return maxCount ; NEW_LINE DEDENT DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT str = " zACaAbbaazzC " ; NEW_LINE print ( maxLower ( str ) ) ; NEW_LINE DEDENT |
First uppercase letter in a string ( Iterative and Recursive ) | Function to find string which has first character of each word . ; Driver code | def first ( str ) : NEW_LINE INDENT for i in range ( 0 , len ( str ) ) : NEW_LINE INDENT if ( str [ i ] . istitle ( ) ) : NEW_LINE INDENT return str [ i ] NEW_LINE DEDENT DEDENT return 0 NEW_LINE DEDENT str = " geeksforGeeKS " NEW_LINE res = first ( str ) NEW_LINE if ( res == 0 ) : NEW_LINE INDENT print ( " No β uppercase β letter " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( res ) NEW_LINE DEDENT |
Count maximum | Python3 implementation for counting maximum length palindromes ; factorial of a number ; function to count maximum length palindromes . ; Count number of occurrence of a charterer in the string ; k = 0 Count of singles num = 0 numerator of result den = 1 denominator of result ; if frequency is even fi = ci / 2 ; if frequency is odd fi = ci - 1 / 2. ; sum of all frequencies ; product of factorial of every frequency ; if all character are unique so there will be no pallindrome , so if num != 0 then only we are finding the factorial ; k are the single elements that can be placed in middle ; Driver Code | import math as mt NEW_LINE def fact ( n ) : NEW_LINE INDENT ans = 1 NEW_LINE for i in range ( 1 , n + 1 ) : NEW_LINE INDENT ans = ans * i NEW_LINE DEDENT return ( ans ) NEW_LINE DEDENT def numberOfPossiblePallindrome ( string , n ) : NEW_LINE INDENT mp = dict ( ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT if string [ i ] in mp . keys ( ) : NEW_LINE INDENT mp [ string [ i ] ] += 1 NEW_LINE DEDENT else : NEW_LINE INDENT mp [ string [ i ] ] = 1 NEW_LINE DEDENT DEDENT fi = 0 NEW_LINE for it in mp : NEW_LINE INDENT if ( mp [ it ] % 2 == 0 ) : NEW_LINE INDENT fi = mp [ it ] // 2 NEW_LINE DEDENT else : NEW_LINE INDENT fi = ( mp [ it ] - 1 ) // 2 NEW_LINE k += 1 NEW_LINE DEDENT num = num + fi NEW_LINE den = den * fact ( fi ) NEW_LINE DEDENT if ( num != 0 ) : NEW_LINE INDENT num = fact ( num ) NEW_LINE DEDENT ans = num // den NEW_LINE if ( k != 0 ) : NEW_LINE INDENT ans = ans * k NEW_LINE DEDENT return ( ans ) NEW_LINE DEDENT string = " ababab " NEW_LINE n = len ( string ) NEW_LINE print ( numberOfPossiblePallindrome ( string , n ) ) NEW_LINE |
Counting even decimal value substrings in a binary string | Python3 Program to count all even decimal value substring ; Generate all substring in arr [ 0. . n - 1 ] ; Store the count ; Pick starting point ; Pick ending point ; Substring between current starting and ending points ; increment power of 2 by one ; Driver code | import math NEW_LINE def evenDecimalValue ( str , n ) : NEW_LINE INDENT result = 0 NEW_LINE for i in range ( 0 , n ) : NEW_LINE INDENT for j in range ( i , n ) : NEW_LINE INDENT decimalValue = 0 ; NEW_LINE powerOf2 = 1 ; NEW_LINE for k in range ( i , j + 1 ) : NEW_LINE INDENT decimalValue += ( ( int ( str [ k ] ) - 0 ) * powerOf2 ) NEW_LINE powerOf2 *= 2 NEW_LINE DEDENT if ( decimalValue % 2 == 0 ) : NEW_LINE INDENT result += 1 NEW_LINE DEDENT DEDENT DEDENT return result NEW_LINE DEDENT str = "10010" NEW_LINE n = 5 NEW_LINE print ( evenDecimalValue ( str , n ) ) NEW_LINE |
Create a new string by alternately combining the characters of two halves of the string in reverse | Function performing calculations ; Calculating the two halves of string s as first and second . The final string p ; It joins the characters to final string in reverse order ; It joins the characters to final string in reverse order ; Driver code ; Calling function | def solve ( s ) : NEW_LINE INDENT l = len ( s ) NEW_LINE x = l // 2 NEW_LINE y = l NEW_LINE p = " " NEW_LINE while ( x > 0 and y > l / 2 ) : NEW_LINE INDENT p = p + s [ x - 1 ] NEW_LINE x = x - 1 NEW_LINE p = p + s [ y - 1 ] NEW_LINE y = y - 1 NEW_LINE DEDENT if ( y > l // 2 ) : NEW_LINE INDENT p = p + s [ y - 1 ] NEW_LINE y = y - 1 NEW_LINE DEDENT print ( p ) NEW_LINE DEDENT s = " sunshine " NEW_LINE solve ( s ) NEW_LINE |
Make a lexicographically smallest palindrome with minimal changes | Function to create a palindrome ; Count the occurrences of every character in the string ; Create a string of characters with odd occurrences ; Change the created string upto middle element and update count to make sure that only one odd character exists . ; decrease the count of character updated ; Create three strings to make first half second half and middle one . ; characters with even occurrences ; fill the first half . ; character with odd occurrence ; fill the first half with half of occurrence except one ; For middle element ; create the second half by reversing the first half . ; Driver Code | def palindrome ( s : str , n : int ) -> int : NEW_LINE INDENT cnt = dict ( ) NEW_LINE R = [ ] NEW_LINE for i in range ( n ) : NEW_LINE INDENT a = s [ i ] NEW_LINE if a in cnt : NEW_LINE INDENT cnt [ a ] += 1 NEW_LINE DEDENT else : NEW_LINE INDENT cnt [ a ] = 1 NEW_LINE DEDENT DEDENT i = ' a ' NEW_LINE while i <= ' z ' : NEW_LINE INDENT if i in cnt and cnt [ i ] % 2 != 0 : NEW_LINE INDENT R += i NEW_LINE DEDENT i = chr ( ord ( i ) + 1 ) NEW_LINE DEDENT l = len ( R ) NEW_LINE j = 0 NEW_LINE for i in range ( l - 1 , ( l // 2 ) - 1 , - 1 ) : NEW_LINE INDENT if R [ i ] in cnt : NEW_LINE INDENT cnt [ R [ i ] ] -= 1 NEW_LINE DEDENT else : NEW_LINE INDENT cnt [ R [ i ] ] = - 1 NEW_LINE DEDENT R [ i ] = R [ j ] NEW_LINE if R [ j ] in cnt : NEW_LINE INDENT cnt [ R [ j ] ] += 1 NEW_LINE DEDENT else : NEW_LINE INDENT cnt [ R [ j ] ] = 1 NEW_LINE DEDENT j += 1 NEW_LINE DEDENT first , middle , second = " " , " " , " " NEW_LINE i = ' a ' NEW_LINE while i <= ' z ' : NEW_LINE INDENT if i in cnt : NEW_LINE INDENT if cnt [ i ] % 2 == 0 : NEW_LINE INDENT j = 0 NEW_LINE while j < cnt [ i ] // 2 : NEW_LINE INDENT first += i NEW_LINE j += 1 NEW_LINE DEDENT DEDENT else : NEW_LINE INDENT j = 0 NEW_LINE while j < ( cnt [ i ] - 1 ) // 2 : NEW_LINE INDENT first += i NEW_LINE j += 1 NEW_LINE DEDENT middle += i NEW_LINE DEDENT DEDENT i = chr ( ord ( i ) + 1 ) NEW_LINE DEDENT second = first NEW_LINE second = ' ' . join ( reversed ( second ) ) NEW_LINE resultant = first + middle + second NEW_LINE print ( resultant ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT S = " geeksforgeeks " NEW_LINE n = len ( S ) NEW_LINE palindrome ( S , n ) NEW_LINE DEDENT |
Program for length of a string using recursion | Python program to calculate length of a string using recursion ; Function to calculate length ; if we reach at the end of the string ; Driver Code | str = " GeeksforGeeks " NEW_LINE def string_length ( str ) : NEW_LINE INDENT if str == ' ' : NEW_LINE INDENT return 0 NEW_LINE DEDENT else : NEW_LINE INDENT return 1 + string_length ( str [ 1 : ] ) NEW_LINE DEDENT DEDENT print ( string_length ( str ) ) NEW_LINE |
Count consonants in a string ( Iterative and recursive methods ) | Function to check for consonant ; To handle lower case ; To check is character is Consonant ; Driver code | def isConsonant ( ch ) : NEW_LINE INDENT ch = ch . upper ( ) NEW_LINE return not ( ch == ' A ' or ch == ' E ' or ch == ' I ' or ch == ' O ' or ch == ' U ' ) and ord ( ch ) >= 65 and ord ( ch ) <= 90 NEW_LINE DEDENT def totalConsonants ( string ) : NEW_LINE INDENT count = 0 NEW_LINE for i in range ( len ( string ) ) : NEW_LINE INDENT if ( isConsonant ( string [ i ] ) ) : NEW_LINE INDENT count += 1 NEW_LINE DEDENT DEDENT return count NEW_LINE DEDENT string = " abc β de " NEW_LINE print ( totalConsonants ( string ) ) NEW_LINE |
Count consonants in a string ( Iterative and recursive methods ) | Function to check for consonant ; To handle lower case ; To count total number of consonants from 0 to n - 1 ; Driver code | def isConsonant ( ch ) : NEW_LINE INDENT ch = ch . upper ( ) NEW_LINE return not ( ch == ' A ' or ch == ' E ' or ch == ' I ' or ch == ' O ' or ch == ' U ' ) and ord ( ch ) >= 65 and ord ( ch ) <= 90 NEW_LINE DEDENT def totalConsonants ( string , n ) : NEW_LINE INDENT if n == 1 : NEW_LINE INDENT return isConsonant ( string [ 0 ] ) NEW_LINE DEDENT return totalConsonants ( string , n - 1 ) + isConsonant ( string [ n - 1 ] ) NEW_LINE DEDENT string = " abc β de " NEW_LINE print ( totalConsonants ( string , len ( string ) ) ) NEW_LINE |
Subsets and Splits