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: a) Every integer is between [0,2^n -1] inclusive b) The sequence begins with 0 c) An integer appears at most one times in the sequence d)The
(bit_count: int)
| 1 | def gray_code(bit_count: int) -> list: |
| 2 | """ |
| 3 | Takes in an integer n and returns a n-bit |
| 4 | gray code sequence |
| 5 | An n-bit gray code sequence is a sequence of 2^n |
| 6 | integers where: |
| 7 | |
| 8 | a) Every integer is between [0,2^n -1] inclusive |
| 9 | b) The sequence begins with 0 |
| 10 | c) An integer appears at most one times in the sequence |
| 11 | d)The binary representation of every pair of integers differ |
| 12 | by exactly one bit |
| 13 | e) The binary representation of first and last bit also |
| 14 | differ by exactly one bit |
| 15 | |
| 16 | >>> gray_code(2) |
| 17 | [0, 1, 3, 2] |
| 18 | |
| 19 | >>> gray_code(1) |
| 20 | [0, 1] |
| 21 | |
| 22 | >>> gray_code(3) |
| 23 | [0, 1, 3, 2, 6, 7, 5, 4] |
| 24 | |
| 25 | >>> gray_code(-1) |
| 26 | Traceback (most recent call last): |
| 27 | ... |
| 28 | ValueError: The given input must be positive |
| 29 | |
| 30 | >>> gray_code(10.6) |
| 31 | Traceback (most recent call last): |
| 32 | ... |
| 33 | TypeError: unsupported operand type(s) for <<: 'int' and 'float' |
| 34 | """ |
| 35 | |
| 36 | # bit count represents no. of bits in the gray code |
| 37 | if bit_count < 0: |
| 38 | raise ValueError("The given input must be positive") |
| 39 | |
| 40 | # get the generated string sequence |
| 41 | sequence = gray_code_sequence_string(bit_count) |
| 42 | # |
| 43 | # convert them to integers |
| 44 | for i in range(len(sequence)): |
| 45 | sequence[i] = int(sequence[i], 2) |
| 46 | |
| 47 | return sequence |
| 48 | |
| 49 | |
| 50 | def gray_code_sequence_string(bit_count: int) -> list: |
nothing calls this directly
no test coverage detected