您的位置:首页 > 编程语言 > Python开发

格雷码 Python编写

2015-12-15 16:02 627 查看
生成格雷码

在一组数的编码中,若任意两个相邻的代码只有一位二进制数不同, 则称这种编码为格雷码(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']


关于格雷码的转换方法,查看百度百科 转换方法一节

http://baike.baidu.com/view/358724.htm
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: