八皇后问题

xiaoxiao2021-02-28  7

《python基础教程第二版》中第九章有一个八皇后问题:

在研究代码的时候我但是没有好好理解元组的定义,所以在一条语句处卡了很久:

if abs(state[i] - nextX) in (0, nextY - i): 这个元组(0,边长),因为是对角线,所以高度和宽度是一样的,等腰直角三角形。所以可以用nextY-i表示。

还有一点就是自己对生成器还是不太明白,仅仅是照着书上敲的,yield。希望以后用新的算法再实现一下

全部代码如下所以:

import random def conflict(state, nextX): nextY = len(state) for i in range(nextY): if abs(state[i] - nextX) in (0, nextY - i): return True return False def 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,) + result def prettyprint(solution): def line(pos, length=len(solution)): return '.' * (pos) + 'X' + '.' * (length - pos - 1) for pos in solution: print line(pos) prettyprint(random.choice(list(queens(8))))

转载请注明原文地址: https://www.6miu.com/read-750244.html

最新回复(0)