Example of the gray code generation function implemented by Python, python gray

Source: Internet
Author: User

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:

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.