用python的生成器yield轻松解决8皇后的问题以及斐波拉契数列

来源:互联网 发布:安装美工刀片的圆规 编辑:程序博客网 时间:2024/06/07 05:31
def conflict(state, nextX):    nextY = len(state)    for i in range(nextY):        if abs(state[i] - nextX) in (0, nextY - i):            return True    return Falsedef queens(num=8, state=()):    for pos in range(num):        if not conflict(state, pos):            if len(state) == num -1:                yield (pos, )            else:                for result in queens(num, state+(pos,)):                    yield (pos,) + resultprint(list(queens(8)))print(len(list(queens(8))))
# 不使用生成器def fib1(max):    res = []    n, a, b = 0, 0, 1    while n < max:        res.append(a + b)        a, b = b, a + b        n += 1    return res# 使用生成器def fib2(max):    n, a, b = 0, 0, 1    while n < max:        yield b        a, b = b, a + b        n += 1f1 = fib1(5)print(f1)for i in fib2(10):    print(i)
原创粉丝点击