04.08.2014 Views

o_18ufhmfmq19t513t3lgmn5l1qa8a.pdf

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

200 CHAPTER 9 ■ MAGIC METHODS, PROPERTIES, AND ITERATORS<br />

>>> len(list(queens(8)))<br />

92<br />

Wrapping It Up<br />

Before leaving the queens, let’s make the output a bit more understandable. Clear output is<br />

always a good thing because it makes it easier to spot bugs, among other things.<br />

def prettyprint(solution):<br />

def line(pos, length=len(solution)):<br />

return '. ' * (pos) + 'X ' + '. ' * (length-pos-1)<br />

for pos in solution:<br />

print line(pos)<br />

Note that I’ve made a little helper function inside prettyprint. I put it there because I assumed<br />

I wouldn’t need it anywhere outside. In the following, I print out a random solution to satisfy<br />

myself that it is correct:<br />

>>> import random<br />

>>> prettyprint(random.choice(list(queens(8))))<br />

. . . . . X . .<br />

. X . . . . . .<br />

. . . . . . X .<br />

X . . . . . . .<br />

. . . X . . . .<br />

. . . . . . . X<br />

. . . . X . . .<br />

. . X . . . . .<br />

This “drawing” corresponds to the diagram in Figure 9-2. Fun to play with Python, isn’t it?<br />

Figure 9-2. One of many possible solutions to the Eight Queens problem

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!