bit_manipulation.gray_code_sequence

Functions

gray_code(→ list[int])

Takes in an integer n and returns a n-bit

gray_code_sequence_string(→ list[str])

Will output the n-bit Gray code sequence as a

Module Contents

bit_manipulation.gray_code_sequence.gray_code(bit_count: int) list[int]

Takes in an integer n and returns a n-bit gray code sequence An n-bit gray code sequence is a sequence of 2^n integers where:

  1. Every integer is between [0,2^n -1] inclusive

  2. The sequence begins with 0

  3. An integer appears at most one time in the sequence

  4. The binary representation of every pair of integers differ by exactly one bit

  5. The binary representation of first and last bit also differ by exactly one bit

>>> gray_code(0)
[0]
>>> gray_code(2)
[0, 1, 3, 2]
>>> gray_code(1)
[0, 1]
>>> gray_code(3)
[0, 1, 3, 2, 6, 7, 5, 4]
>>> gray_code(-1)
Traceback (most recent call last):
    ...
ValueError: The given input must be positive
>>> gray_code(10.6)
Traceback (most recent call last):
    ...
TypeError: unsupported operand type(s) for <<: 'int' and 'float'
bit_manipulation.gray_code_sequence.gray_code_sequence_string(bit_count: int) list[str]

Will output the n-bit Gray code sequence as a string of bits

>>> gray_code_sequence_string(0)
['0']
>>> gray_code_sequence_string(2)
['00', '01', '11', '10']
>>> gray_code_sequence_string(1)
['0', '1']