Skip to content

Commit 9619ee1

Browse files
authored
Improve typing annotations, doctests, and docstrings in gray_code_sequence (#15205)
1 parent d255f97 commit 9619ee1

1 file changed

Lines changed: 14 additions & 13 deletions

File tree

bit_manipulation/gray_code_sequence.py

Lines changed: 14 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
def gray_code(bit_count: int) -> list:
1+
def gray_code(bit_count: int) -> list[int]:
22
"""
33
Takes in an integer n and returns a n-bit
44
gray code sequence
@@ -7,12 +7,15 @@ def gray_code(bit_count: int) -> list:
77
88
a) Every integer is between [0,2^n -1] inclusive
99
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
10+
c) An integer appears at most one time in the sequence
11+
d) The binary representation of every pair of integers differ
1212
by exactly one bit
1313
e) The binary representation of first and last bit also
1414
differ by exactly one bit
1515
16+
>>> gray_code(0)
17+
[0]
18+
1619
>>> gray_code(2)
1720
[0, 1, 3, 2]
1821
@@ -37,21 +40,19 @@ def gray_code(bit_count: int) -> list:
3740
if bit_count < 0:
3841
raise ValueError("The given input must be positive")
3942

40-
# get the generated string sequence
43+
# get the generated string sequence and convert them to integers
4144
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
45+
return [int(code, 2) for code in sequence]
4846

4947

50-
def gray_code_sequence_string(bit_count: int) -> list:
48+
def gray_code_sequence_string(bit_count: int) -> list[str]:
5149
"""
52-
Will output the n-bit grey sequence as a
50+
Will output the n-bit Gray code sequence as a
5351
string of bits
5452
53+
>>> gray_code_sequence_string(0)
54+
['0']
55+
5556
>>> gray_code_sequence_string(2)
5657
['00', '01', '11', '10']
5758
@@ -73,7 +74,7 @@ def gray_code_sequence_string(bit_count: int) -> list:
7374
# recursive answer will generate answer for n-1 bits
7475
smaller_sequence = gray_code_sequence_string(bit_count - 1)
7576

76-
sequence = []
77+
sequence: list[str] = []
7778

7879
# append 0 to first half of the smaller sequence generated
7980
for i in range(seq_len // 2):

0 commit comments

Comments
 (0)