格雷码 Python编写
2015-12-15 16:02
627 查看
生成格雷码
在一组数的编码中,若任意两个相邻的代码只有一位二进制数不同, 则称这种编码为格雷码(Gray Code),请编写一个函数,使用递归的方法生成N位的格雷码。
给定一个整数n,请返回n位的格雷码,顺序为从0开始。
结果
关于格雷码的转换方法,查看百度百科 转换方法一节
http://baike.baidu.com/view/358724.htm
在一组数的编码中,若任意两个相邻的代码只有一位二进制数不同, 则称这种编码为格雷码(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
相关文章推荐
- Python subprocess模块学习总结
- Python正则表达式指南
- 【updating】python读书笔记-The Django Book2.0(for django1.4)
- Python 函数式编程
- python 使用 urllib2 抓取网页内容
- python机器学习之 K-近邻算法
- python引用与上级目录同目录文件夹下的文件方法
- 安装第三方库出现 Python version 2.7 required, which was not found in the registry
- python的yield作用解析
- python rpc client demo
- Python实现冒泡排序
- python cython 模块(2)
- Eclipse和PyDev构建Python开发环境
- Python基础:1.数据类型(列表)
- python print
- python爬虫基础
- kmeans聚类的简介和代码(python)
- 利用python定位网页上的元素
- Python中的logger和handler到底是个什么鬼
- python cython 模块(1)