八皇后问题学习 enumerate 和 permutations
permutations 生成123…9的全排列,共9!个
enumerate 提取横纵坐标
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from itertools import permutations as perm | |
# (1, 5, 8, 6, 3, 7, 2, 4)表示棋子位置:i.imgbox.com/VHrKYxDG.png | |
cols = perm(range(1,9)) #所有可能a88=40320 | |
# 保证对角线 | |
def OK(s): | |
sl = set(r-c for r,c in enumerate(s)) # y=x | |
bs = set(r+c for r,c in enumerate(s)) # y=-x | |
return len(sl) == len(bs) == 8 | |
solutions = [c for c in cols if OK(c)] | |
for i,s in enumerate(solutions,1): | |
print i,":",s |