Example of the gray code generation function implemented by Python, python gray
This example describes how to generate a gray code in Python. We will share this with you for your reference. The details are as follows:
Problem
In the Code of a set of numbers, if any two adjacent codes have only one binary number, this encoding is called Gray Code. Please write a function, use recursive methods to generate N-bit gray code.
Solution:
If an integer n is given, return the Gray Code of n digits. The order starts from 0.
Test example:
Return Value: ["0", "1"]
The question is very concise, and the example is very cold ......
There are some subtle relationships.
After discovering this rule, the code is naturally easy to write.
#-*-Coding: UTF-8-*-class GrayCode: def getGray (self, n): # write code here global 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 "helper's house Test Result:" print gary. getGray (3)
Running result: