Python Program to Generate Gray Codes using Recursion

PythonServer Side ProgrammingProgramming

When it is required to generate gray codes with the help of recursion, a method is defined, that creates an empty list and appends values 0 and 1 to it. Multiple ‘for’ loops are used to generate the gray code within the function.

Below is the demonstration of the same −

Example

 Live Demo

import math as mt
def generate_gray_list(my_val):
   if (my_val <= 0):
      return
   my_list = list()
   my_list.append("0")
   my_list.append("1")
   i = 2
   j = 0
   while(True):
      if i >= 1 << my_val:
         break
      for j in range(i - 1, -1, -1):
         my_list.append(my_list[j])
      for j in range(i):
         my_list[j] = "0" + my_list[j]
      for j in range(i, 2 * i):
         my_list[j] = "1" + my_list[j]
      i = i << 1
   for i in range(len(my_list)):
      print(my_list[i])
my_num = 3
print("The number is :")
print(my_num)
print("Method to convert gray code to binary is being called...")
generate_gray_list(my_num)

Output

The number is :
3
Method to convert gray code to binary is being called...
000
001
011
010
110
111
101
100

Explanation

  • The required packages are imported.

  • A method is defined, that creates an empty list.

  • It appends 0 and 1 to the list.

  • Multiple ‘for’ loops are used to iterate within the range of 0 and 2.

  • The left shift operator is used on the iterator and compared with the number.

  • Outside the method, it is called by passing relevant parameter.

  • The output is displayed on the console.

raja
Published on 19-Apr-2021 10:43:43
Advertisements