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

#!/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)
posted @ 2015-09-15 15:23  coder_zhang1  阅读(144)  评论(0编辑  收藏  举报