Generating Lyndon words of length n | Python implementation of the above approach ; To store the indices of the characters ; Loop till w is not empty ; Incrementing the last character ; Repeating w to get a n - length string ; Removing the last character as long it is equal to the largest character in S
n = 2 NEW_LINE S = [ '0' , '1' , '2' ] NEW_LINE k = len ( S ) NEW_LINE S . sort ( ) NEW_LINE w = [ - 1 ] NEW_LINE while w : NEW_LINE INDENT w [ - 1 ] += 1 NEW_LINE m = len ( w ) NEW_LINE if m == n : NEW_LINE INDENT print ( ' ' . join ( S [ i ] for i in w ) ) NEW_LINE DEDENT while len ( w ) < n : NEW_LINE INDENT w . append ( w [ - m ] ) NEW_LINE DEDENT while w and w [ - 1 ] == k - 1 : NEW_LINE INDENT w . pop ( ) NEW_LINE DEDENT DEDENT