python生成器-8皇后问题

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
#def flatten(nested):
# try:
# try:
# nested + ''
# except TypeError:
# pass
# else:
# raise TypeError
# for sublist in nested:
# for element in flatten(sublist):
# yield element
# except TypeError:
# yield nested



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))

import random
prettyprint(random.choice(list(queens(8))))
print(len(list(queens(8))))
//

. . X . . . . .
. . . . X . . .
. . . . . . . X
. . . X . . . .
X . . . . . . .
. . . . . . X .
. X . . . . . .
. . . . . X . .
92