def grayCode( n ):
    # For printing convenience,
    # each code is represented as a string
    # of 0s and 1s separated by spaces.

    if n == 1: return ["0", "1"]

    # obtain smaller code recursively
    gc0 = grayCode( n-1 )         # first half
    gc1 = list( reversed(gc0) )   # second half

    # prepend 0s and 1s to the smaller code
    for i in range( len(gc0) ):
        gc0[i] = "0 " + gc0[i]
    for i in range( len(gc1) ):
        gc1[i] = "1 " + gc1[i]

    return gc0 + gc1

# ------------------------------------------------
# Experiments:

maxCodeLen = 6
for codeLen in range( 1, maxCodeLen ):
    print( "n =", codeLen )  
    for code in grayCode( codeLen ):
        print( code )
    print()
