Generate n | This function generates all n bit Gray codes and prints the generated codes ; Base case ; Recursive case ; Append 0 to the first half ; Append 1 to the second half ; Function to generate the Gray code of N bits ; Print contents of arr ; Driver Code
def generateGray ( n ) : NEW_LINE INDENT if ( n <= 0 ) : NEW_LINE INDENT return [ "0" ] NEW_LINE DEDENT if ( n == 1 ) : NEW_LINE INDENT return [ "0" , "1" ] NEW_LINE DEDENT recAns = generateGray ( n - 1 ) NEW_LINE mainAns = [ ] NEW_LINE for i in range ( len ( recAns ) ) : NEW_LINE INDENT s = recAns [ i ] NEW_LINE mainAns . append ( "0" + s ) NEW_LINE DEDENT for i in range ( len ( recAns ) - 1 , - 1 , - 1 ) : NEW_LINE INDENT s = recAns [ i ] NEW_LINE mainAns . append ( "1" + s ) NEW_LINE DEDENT return mainAns NEW_LINE DEDENT def generateGrayarr ( n ) : NEW_LINE INDENT arr = generateGray ( n ) NEW_LINE print ( * arr , sep =   " " ) NEW_LINE DEDENT generateGrayarr ( 3 ) NEW_LINE