This action will force synchronization from 编程语言算法集/Python, which will overwrite any changes that you have made since you forked the repository, and can not be recovered!!!
Synchronous operation will process in the background and will refresh the page when finishing processing. Please be patient.
def gray_code(bit_count: int) -> list:"""Takes in an integer n and returns a n-bitgray code sequenceAn n-bit gray code sequence is a sequence of 2^nintegers where:a) Every integer is between [0,2^n -1] inclusiveb) The sequence begins with 0c) An integer appears at most one times in the sequenced)The binary representation of every pair of integers differby exactly one bite) The binary representation of first and last bit alsodiffer by exactly one bit>>> 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 count represents no. of bits in the gray codeif bit_count < 0:raise ValueError("The given input must be positive")# get the generated string sequencesequence = gray_code_sequence_string(bit_count)## convert them to integersfor i in range(len(sequence)):sequence[i] = int(sequence[i], 2)return sequencedef gray_code_sequence_string(bit_count: int) -> list:"""Will output the n-bit grey sequence as astring of bits>>> gray_code_sequence_string(2)['00', '01', '11', '10']>>> gray_code_sequence_string(1)['0', '1']"""# The approach is a recursive one# Base case achieved when either n = 0 or n=1if bit_count == 0:return ["0"]if bit_count == 1:return ["0", "1"]seq_len = 1 << bit_count # defines the length of the sequence# 1<< n is equivalent to 2^n# recursive answer will generate answer for n-1 bitssmaller_sequence = gray_code_sequence_string(bit_count - 1)sequence = []# append 0 to first half of the smaller sequence generatedfor i in range(seq_len // 2):generated_no = "0" + smaller_sequence[i]sequence.append(generated_no)# append 1 to second half ... start from the end of the listfor i in reversed(range(seq_len // 2)):generated_no = "1" + smaller_sequence[i]sequence.append(generated_no)return sequenceif __name__ == "__main__":import doctestdoctest.testmod()
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。