

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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 Questions & Answers
- A backtracking approach to generate n bit Gray Codes ?
- Binary to Gray code using recursion in C program
- 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
- JavaScript to generate random hex codes of color
- 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
- C++ Program to Find G.C.D Using Recursion
- C++ Program to Calculate Power Using Recursion
Advertisements