MCPcopy Create free account
hub / github.com/TheAlgorithms/Python / gray_code_sequence_string

Function gray_code_sequence_string

bit_manipulation/gray_code_sequence.py:50–88  ·  view source on GitHub ↗

Will output the n-bit grey sequence as a string of bits >>> gray_code_sequence_string(2) ['00', '01', '11', '10'] >>> gray_code_sequence_string(1) ['0', '1']

(bit_count: int)

Source from the content-addressed store, hash-verified

48
49
50def gray_code_sequence_string(bit_count: int) -> list:
51 """
52 Will output the n-bit grey sequence as a
53 string of bits
54
55 >>> gray_code_sequence_string(2)
56 ['00', '01', '11', '10']
57
58 >>> gray_code_sequence_string(1)
59 ['0', '1']
60 """
61
62 # The approach is a recursive one
63 # Base case achieved when either n = 0 or n=1
64 if bit_count == 0:
65 return ["0"]
66
67 if bit_count == 1:
68 return ["0", "1"]
69
70 seq_len = 1 << bit_count # defines the length of the sequence
71 # 1<< n is equivalent to 2^n
72
73 # recursive answer will generate answer for n-1 bits
74 smaller_sequence = gray_code_sequence_string(bit_count - 1)
75
76 sequence = []
77
78 # append 0 to first half of the smaller sequence generated
79 for i in range(seq_len // 2):
80 generated_no = "0" + smaller_sequence[i]
81 sequence.append(generated_no)
82
83 # append 1 to second half ... start from the end of the list
84 for i in reversed(range(seq_len // 2)):
85 generated_no = "1" + smaller_sequence[i]
86 sequence.append(generated_no)
87
88 return sequence
89
90
91if __name__ == "__main__":

Callers 1

gray_codeFunction · 0.85

Calls 1

appendMethod · 0.45

Tested by

no test coverage detected