循环Gray码的生成(递归)

#!/usr/bin/env python
#coding:utf-8

import sys

def gray_code(num, array):
    if num < 1:
        return
    if num == 1:
        array.append('0')
        array.append('1')
        return
    gray_code(num-1, array)
    times = 2 ** (num-1)
    len_ = len(array)
    for i in xrange(times):
        array.append('1' + array[len_-1-i])
    for i in xrange(times):
        array[i] = '0' + array[i]

if __name__ == "__main__":
    if len(sys.argv) != 2:
        print "Usage:./gray_code.py number"
        sys.exit(1)
    number = 0
    try:
        number = int(sys.argv[1])
    except Exception, e:
        print e.message
        sys.exit(1)
    codes = []
    gray_code(number, codes)
    print codes
posted @ 2015-09-15 10:29  coder_zhang1  阅读(277)  评论(0编辑  收藏  举报