Find the n | Python3 implementation of the above approach ; Function to return the nth string in the required sequence ; Length of the resultant string ; Relative index ; Initial string of length len consists of all a 's since the list is sorted ; Convert relative index to Binary form and set 0 = a and 1 = b ; Reverse and return the string ; Driver Code
from math import log2 NEW_LINE def obtain_str ( n ) : NEW_LINE INDENT length = int ( log2 ( n + 1 ) ) NEW_LINE rel_ind = n + 1 - pow ( 2 , length ) NEW_LINE i = 0 NEW_LINE string = " " NEW_LINE for i in range ( length ) : NEW_LINE INDENT string += ' a ' NEW_LINE DEDENT i = 0 NEW_LINE string_list = list ( string ) NEW_LINE while ( rel_ind > 0 ) : NEW_LINE INDENT if ( rel_ind % 2 == 1 ) : NEW_LINE INDENT string_list [ i ] = ' b ' NEW_LINE DEDENT rel_ind //= 2 NEW_LINE i += 1 NEW_LINE DEDENT string_list . reverse ( ) NEW_LINE string = " " . join ( string_list ) NEW_LINE return string NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT n = 11 NEW_LINE print ( obtain_str ( n ) ) NEW_LINE DEDENT