
- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
Python Program to Generate Gray Codes using Recursion
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
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.
- Related Articles
- A backtracking approach to generate n bit Gray Codes ?
- Binary to Gray code using recursion in C program
- C++ Program to convert the Binary number to Gray code using recursion
- Python Program to Reverse a String Using Recursion
- Python Program to Reverse a Stack using Recursion
- Python Program to Display Fibonacci Sequence Using Recursion
- Python Program to Convert Gray Code to Binary
- Python Program to Convert Binary to Gray Code
- Python Program to Flatten a Nested List using Recursion
- Python Program to Flatten a List without using Recursion
- Python Program to Reverse a String without using Recursion
- Python Program to Find the Fibonacci Series Using Recursion
- Python Program to Find the Fibonacci Series without Using Recursion
- JavaScript to generate random hex codes of color
- Python Program to Find the Product of two Numbers Using Recursion

Advertisements