Generate a String from given Strings P and Q based on the given conditions | Function to generate a string S from string P and Q according to the given conditions ; Stores the frequencies ; Counts occurrences of each characters ; Reduce the count of the character which is also present in Q ; Stores the resultant string ; Index in freq [ ] to segregate the string ; Add Q to the resulting string ; Driver Code ; Function call
def manipulateStrings ( P , Q ) : NEW_LINE INDENT freq = [ 0 for i in range ( 26 ) ] ; NEW_LINE for i in range ( len ( P ) ) : NEW_LINE INDENT freq [ ord ( P [ i ] ) - ord ( ' a ' ) ] += 1 NEW_LINE DEDENT for i in range ( len ( Q ) ) : NEW_LINE INDENT freq [ ord ( Q [ i ] ) - ord ( ' a ' ) ] -= 1 NEW_LINE DEDENT sb = " " NEW_LINE pos = ord ( Q [ 0 ] ) - ord ( ' a ' ) NEW_LINE for i in range ( pos + 1 ) : NEW_LINE INDENT while freq [ i ] > 0 : NEW_LINE INDENT sb += chr ( ord ( ' a ' ) + i ) NEW_LINE freq [ i ] -= 1 NEW_LINE DEDENT DEDENT sb += Q NEW_LINE for i in range ( pos + 1 , 26 ) : NEW_LINE INDENT while freq [ i ] > 0 : NEW_LINE INDENT sb += chr ( ord ( ' a ' ) + i ) NEW_LINE freq [ i ] -= 1 NEW_LINE DEDENT DEDENT print ( sb ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT P = " geeksforgeeksfor " ; NEW_LINE Q = " for " ; NEW_LINE manipulateStrings ( P , Q ) ; NEW_LINE DEDENT