Print a number as string of ' A ' and ' B ' in lexicographic order | Python 3 program to implement the above approach ; Function to calculate number of characters in corresponding string of ' A ' and 'B ; Since the minimum number of characters will be 1 ; Calculating number of characters ; Since k length string can represent at most pow ( 2 , k + 1 ) - 2 that is if k = 4 , it can represent at most pow ( 2 , 4 + 1 ) - 2 = 30 so we have to calculate the length of the corresponding string ; return the length of the corresponding string ; Function to print corresponding string of ' A ' and 'B ; Find length of string ; Since the first number that can be represented by k length string will be ( pow ( 2 , k ) - 2 ) + 1 and it will be AAA ... A , k times , therefore , N will store that how much we have to print ; At a particular time , we have to decide whether we have to print ' A ' or ' B ' , this can be check by calculating the value of pow ( 2 , k - 1 ) ; Print new line ; Driver code
from math import pow NEW_LINE ' NEW_LINE def no_of_characters ( M ) : NEW_LINE INDENT k = 1 NEW_LINE while ( True ) : NEW_LINE INDENT if ( pow ( 2 , k + 1 ) - 2 < M ) : NEW_LINE INDENT k += 1 NEW_LINE DEDENT else : NEW_LINE INDENT break NEW_LINE DEDENT DEDENT return k NEW_LINE DEDENT ' NEW_LINE def print_string ( M ) : NEW_LINE INDENT k = no_of_characters ( M ) NEW_LINE N = M - ( pow ( 2 , k ) - 2 ) NEW_LINE while ( k > 0 ) : NEW_LINE INDENT num = pow ( 2 , k - 1 ) NEW_LINE if ( num >= N ) : NEW_LINE INDENT print ( " A " , end = " " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " B " , end = " " ) NEW_LINE N -= num NEW_LINE DEDENT k -= 1 NEW_LINE DEDENT print ( " " , ▁ end ▁ = ▁ " " ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT M = 30 ; NEW_LINE print_string ( M ) NEW_LINE M = 55 NEW_LINE print_string ( M ) NEW_LINE M = 100 NEW_LINE print_string ( M ) NEW_LINE DEDENT