Generate n | Python3 program to generate n - bit Gray codes ; This function generates all n bit Gray codes and prints the generated codes ; base case ; ' arr ' will store all generated codes ; start with one - bit pattern ; Every iteration of this loop generates 2 * i codes from previously generated i codes . ; Enter the prviously generated codes again in arr [ ] in reverse order . Nor arr [ ] has double number of codes . ; append 0 to the first half ; append 1 to the second half ; prcontents of arr [ ] ; Driver Code
import math as mt NEW_LINE def generateGrayarr ( n ) : NEW_LINE INDENT if ( n <= 0 ) : NEW_LINE INDENT return NEW_LINE DEDENT arr = list ( ) NEW_LINE arr . append ( "0" ) NEW_LINE arr . append ( "1" ) NEW_LINE i = 2 NEW_LINE j = 0 NEW_LINE while ( True ) : NEW_LINE INDENT if i >= 1 << n : NEW_LINE INDENT break NEW_LINE DEDENT for j in range ( i - 1 , - 1 , - 1 ) : NEW_LINE INDENT arr . append ( arr [ j ] ) NEW_LINE DEDENT for j in range ( i ) : NEW_LINE INDENT arr [ j ] = "0" + arr [ j ] NEW_LINE DEDENT for j in range ( i , 2 * i ) : NEW_LINE INDENT arr [ j ] = "1" + arr [ j ] NEW_LINE DEDENT i = i << 1 NEW_LINE DEDENT for i in range ( len ( arr ) ) : NEW_LINE INDENT print ( arr [ i ] ) NEW_LINE DEDENT DEDENT generateGrayarr ( 3 ) NEW_LINE