Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Python Program to Generate Gray Codes using Recursion
Gray codes are binary codes where consecutive numbers differ by exactly one bit. Python can generate Gray codes using recursion by building sequences iteratively. This approach uses bit manipulation and string operations to create the complete Gray code sequence.
What are Gray Codes?
Gray codes (also called reflected binary codes) are sequences where adjacent values differ by only one bit position. For example, in 2-bit Gray code: 00 ? 01 ? 11 ? 10, each step changes exactly one bit.
Gray Code Generation Algorithm
The algorithm starts with the base case (0, 1) and recursively builds larger sequences by:
- Reflecting the existing sequence
- Prefixing original sequence with '0'
- Prefixing reflected sequence with '1'
Example
Here's how to generate Gray codes using an iterative approach with recursion principles ?
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
# Reflect the existing sequence
for j in range(i - 1, -1, -1):
my_list.append(my_list[j])
# Add '0' prefix to first half
for j in range(i):
my_list[j] = "0" + my_list[j]
# Add '1' prefix to second half
for j in range(i, 2 * i):
my_list[j] = "1" + my_list[j]
i = i << 1
# Print the generated Gray codes
for i in range(len(my_list)):
print(my_list[i])
my_num = 3
print("The number is :")
print(my_num)
print("Generating Gray codes...")
generate_gray_list(my_num)
The number is : 3 Generating Gray codes... 000 001 011 010 110 111 101 100
Alternative Recursive Implementation
Here's a more traditional recursive approach ?
def generate_gray_recursive(n):
if n <= 0:
return []
if n == 1:
return ["0", "1"]
# Get Gray codes for n-1 bits
smaller_gray = generate_gray_recursive(n - 1)
# Create result list
result = []
# Add '0' prefix to original sequence
for code in smaller_gray:
result.append("0" + code)
# Add '1' prefix to reversed sequence
for code in reversed(smaller_gray):
result.append("1" + code)
return result
# Generate 3-bit Gray codes
gray_codes = generate_gray_recursive(3)
print("3-bit Gray codes:")
for code in gray_codes:
print(code)
3-bit Gray codes: 000 001 011 010 110 111 101 100
How It Works
The algorithm uses these key steps:
- Base case: For 1 bit, return ["0", "1"]
- Recursive step: Get Gray codes for (n-1) bits
- Reflection: Reverse the sequence and append
- Prefixing: Add '0' to original, '1' to reflected sequence
Verification
Let's verify that consecutive codes differ by exactly one bit ?
def hamming_distance(s1, s2):
return sum(c1 != c2 for c1, c2 in zip(s1, s2))
def verify_gray_code(codes):
print("Verifying Gray code property:")
for i in range(len(codes) - 1):
dist = hamming_distance(codes[i], codes[i + 1])
print(f"{codes[i]} ? {codes[i + 1]}: distance = {dist}")
gray_codes = generate_gray_recursive(2)
verify_gray_code(gray_codes)
Verifying Gray code property: 00 ? 01: distance = 1 01 ? 11: distance = 1 11 ? 10: distance = 1
Conclusion
Gray code generation uses recursive principles to build sequences where consecutive values differ by one bit. The reflection method efficiently creates the complete sequence by doubling and prefixing at each step.
