From 7c81c14a2540fabf38b6cb474d64849b8a7ffd67 Mon Sep 17 00:00:00 2001 From: Simran Shrestha Date: Sat, 19 Oct 2024 11:57:28 +0545 Subject: [PATCH] Implement Gray Code and Unit Tests --- algorithms/bit/__init__.py | 3 ++- algorithms/bit/gray_code.py | 25 +++++++++++++++++++++++++ tests/test_bit.py | 24 +++++++++++++++++++++++- 3 files changed, 50 insertions(+), 2 deletions(-) create mode 100644 algorithms/bit/gray_code.py diff --git a/algorithms/bit/__init__.py b/algorithms/bit/__init__.py index fa31d7ed8..e0e6213af 100644 --- a/algorithms/bit/__init__.py +++ b/algorithms/bit/__init__.py @@ -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 * \ No newline at end of file +from .bytes_int_conversion import * +from .gray_code import * \ No newline at end of file diff --git a/algorithms/bit/gray_code.py b/algorithms/bit/gray_code.py new file mode 100644 index 000000000..40698806b --- /dev/null +++ b/algorithms/bit/gray_code.py @@ -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 diff --git a/tests/test_bit.py b/tests/test_bit.py index c494a9762..7a3aba596 100644 --- a/tests/test_bit.py +++ b/tests/test_bit.py @@ -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 @@ -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()