Python实现的生成格雷码功能示例,python格雷
Python实现的生成格雷码功能示例,python格雷
本文实例讲述了Python实现的生成格雷码功能。分享给大家供大家参考,具体如下:
问题
在一组数的编码中,若任意两个相邻的代码只有一位二进制数不同, 则称这种编码为格雷码(Gray Code),请编写一个函数,使用递归的方法生成N位的格雷码。
解决方法:
给定一个整数n,请返回n位的格雷码,顺序为从0开始。
测试样例:
返回:["0","1"]
题目很刁钻,题干很简洁,样例很高冷……
其中有一些微妙的关系
发现了这个规律之后,代码自然就很好写了
# -*- coding:utf-8 -*- class GrayCode: def getGray(self, n): # write code here global maxn maxn = n return GrayCode.getGrace(self, ['0', '1'], 1) def getGrace(self, list_grace, n): global maxn if n >= maxn: return list_grace list_befor, list_after = [], [] for i in xrange(len(list_grace)): list_befor.append('0' + list_grace[i]) list_after.append('1' + list_grace[-(i + 1)]) return GrayCode.getGrace(self, list_befor + list_after, n + 1) gary = GrayCode() print "帮客之家测试结果:" print gary.getGray(3)
运行结果:
更多关于Python相关内容可查看本站专题:《Python字符串操作技巧汇总》、《Python数据结构与算法教程》、《Python函数使用技巧总结》、《Python入门与进阶经典教程》及《Python文件与目录操作技巧汇总》
希望本文所述对大家Python程序设计有所帮助。
相关内容
- python爬取拉勾网职位数据的方法,python拉勾
- 详解Python之unittest单元测试代码,pythonunittest
- python中的set实现不重复的排序原理,pythonset排序原理
- Python动刷新抢12306火车票的代码(附源码),python12306
- python命令行解析之parse_known_args()函数和parse_args()使用
- python实现壁纸批量下载代码实例,python壁纸
- python实现闹钟定时播放音乐功能,python播放音乐
- python使用pandas实现数据分割实例代码,pythonpandas
- Python使用requests发送POST请求实例代码,pythonrequests
- Python实现PS图像调整颜色梯度效果示例,python梯度
评论关闭