欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

循环Gray码的生成(非递归)

程序员文章站 2022-07-12 12:43:29
...
#!/usr/bin/env python
#coding:utf-8

import sys

def gray_code(n):
    if n < 1:
        return []
    n += 1
    array = ["0", "1"]
    for i in xrange(2, n):
        times = 2 ** (i-1)
        for j in xrange(times):
            array.append("1" + array[times-1-j])
        for j in xrange(times):
            array[j] = "0" + array[j]
    return array

if __name__ == "__main__":
    if len(sys.argv) != 2:
        print "Usage: gray_code_no_rev.py number"
        sys.exit(1)
    number = 0
    try:
        number = int(sys.argv[1])
    except Exception, e:
        print e.message
        sys.exit(1)
    print gray_code(number)