How to Generate Gray Codes from Recursion in Python


This example tells how to create a Gray code through recursion given an input number with Python.

Source Code

#! /usr/bin/env python3
# -*- coding: utf-8 -*-

def grayCode(n):
    """Return n bits Gray code as a list"""
    if n == 0:
        return [""]
    frontHalfLast = grayCode(n - 1)
    backHalfLast = reversed(grayCode(n - 1))
    frontHalf = ["0" + code for code in frontHalfLast]
    backHalf = ["1" + code for code in backHalfLast]

    return frontHalf + backHalf

n = int(input("Please enter the number of bits: "))
codes = grayCode(n)
print("All {} bits Gray code are: ".format(n), codes)

Output:

Please enter the number of bits: 3
All 3 bits Gray code are: ['000', '001', '011', '010', '110', '111', '101', '100']

Please enter the number of bits: 4
All 4 bits Gray code are: ['0000', '0001', '0011', '0010', '0110', '0111', '0101', '0100', '1100', '1101', '1111', '1110', '1010', '1011', '1001', '1000']
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments
Advertisement