非线性递归函数转化为迭代函数举例

def moves_three(n, a=0, b=1, c=2):
    '''give a int -> return a list '''
    if n==1:
        return ((a,c),)
    return moves_three(n-1,a,c,b)+\
           ((a,c),)+\
           moves_three(n-1,b,a,c)

def moves(n, a=0, b=1, c=2):
    stack = [(True, n, a, b, c)]
    while stack:
        tag, n, a, b, c = stack.pop()
        print(tag, n, a, b, c)
        if n == 1:
            yield a, c
        elif tag:
            stack.append((False, n, a, b, c))
            stack.append((True, n-1, a, c, b))
        else:
            yield a, c
            stack.append((True, n-1, b, a, c))

 

posted @ 2014-02-23 13:59  LisPythoniC  阅读(228)  评论(0编辑  收藏  举报