Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Implement Gray Code Generator with Unit Tests for n-bit Sequences #932

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion algorithms/bit/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,4 +16,5 @@
from .count_flips_to_convert import *
from .flip_bit_longest_sequence import *
from .binary_gap import *
from .bytes_int_conversion import *
from .bytes_int_conversion import *
from .gray_code import *
25 changes: 25 additions & 0 deletions algorithms/bit/gray_code.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
"""
Gray Code Generator

Gray code is a binary numeral system where two successive values differ by only one bit. This function generates a sequence of n-bit Gray codes, where n is the number of bits.
"""


def gray_code(n):
"""
Generate the sequence of n-bit Gray code.

:param n: Number of bits for the Gray code
:return: List of Gray code sequence in decimal representation
"""
if n == 0:
return [0]

# Recursive step: generate (n-1)-bit Gray code
previous_gray = gray_code(n - 1)

# Mirror the previous Gray code
new_gray = [(1 << (n - 1)) | i for i in reversed(previous_gray)]

# Concatenate the old and new mirrored Gray code
return previous_gray + new_gray
24 changes: 23 additions & 1 deletion tests/test_bit.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,8 @@
has_alternative_bit, has_alternative_bit_fast,
insert_one_bit, insert_mult_bits,
remove_bit,
binary_gap
binary_gap,
gray_code
)

import unittest
Expand Down Expand Up @@ -270,5 +271,26 @@ def test_binary_gap(self):
self.assertEqual(4, binary_gap(145))


class TestGrayCode(unittest.TestCase):
"""Unit tests for the Gray Code generator."""

def test_0_bit_gray_code(self):
self.assertEqual(gray_code(0), [0])

def test_1_bit_gray_code(self):
self.assertEqual(gray_code(1), [0, 1])

def test_2_bit_gray_code(self):
self.assertEqual(gray_code(2), [0, 1, 3, 2])

def test_3_bit_gray_code(self):
self.assertEqual(gray_code(3), [0, 1, 3, 2, 6, 7, 5, 4])

def test_4_bit_gray_code(self):
self.assertEqual(gray_code(4), [
0, 1, 3, 2, 6, 7, 5, 4, 12, 13, 15, 14, 10, 11, 9, 8
])


if __name__ == '__main__':
unittest.main()