格雷碼 Python編寫
阿新 • • 發佈:2019-02-06
生成格雷碼
在一組數的編碼中,若任意兩個相鄰的程式碼只有一位二進位制數不同, 則稱這種編碼為格雷碼(Gray Code),請編寫一個函式,使用遞迴的方法生成N位的格雷碼。
給定一個整數n,請返回n位的格雷碼,順序為從0開始。
class GrayCode:
def __init__(self):
self.base = ["0", "1"]
def getNext(self , prelist,z_or_one):
output = []
for code in prelist:
new_code = "%s%s" % (z_or_one,code)
output.append(new_code)
if z_or_one == 1:
output.reverse()
return output
def gray(self):
haf1 = self.getNext(self.base, 0)
haf2 = self.getNext(self.base, 1)
ret = haf1 + haf2
self.base = ret
def getGray (self, n):
for i in range(n-1):
self.gray()
return self.base
a = GrayCode()
print a.getGray(3)
結果
['000', '001', '011', '010', '110', '111', '101', '100']