Search code examples
pythonalgorithmrecursiongray-code

Generating Gray codes recursively without initialising the base case outside of the function


I tried generating Gray codes in Python. This code works correctly:

def gray_code(g, n):
    k = len(g)
    if n <= 0:
        return

    else:
        for i in range (k - 1, -1, -1):
            char = '1' + g[i]
            g.append(char)
        for i in range (k - 1, -1, -1):
            g[i] = '0' + g[i]

        gray_code(g, n - 1)

def main():
    n = int(raw_input())
    g = ['0', '1']
    gray_code(g, n - 1)
    if n >= 1:
        for i in range(len(g)):
            print g[i],

main()

The issue is that I am initialising the base case (n=1, [0, 1]) in the main function and passing it to gray_code function to compute the rest.

I want to generate all the Gray codes inside the function itself including the base case. How do I do that?


Solution

  • def gray_code(n):
        def gray_code_recurse (g,n):
            k=len(g)
            if n<=0:
                return
    
            else:
                for i in range (k-1,-1,-1):
                    char='1'+g[i]
                    g.append(char)
                for i in range (k-1,-1,-1):
                    g[i]='0'+g[i]
    
                gray_code_recurse (g,n-1)
    
        g=['0','1']
        gray_code_recurse(g,n-1)
        return g
    
    def main():
        n=int(raw_input())
        g = gray_code (n)
    
        if n>=1:
            for i in range (len(g)):
                print g[i],
    
    main()