16.01.2014 Views

Beginning Python - From Novice to Professional

Beginning Python - From Novice to Professional

Beginning Python - From Novice to Professional

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

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

def queens(num, state):<br />

if len(state) == num-1:<br />

for pos in range(num):<br />

if not conflict(state, pos):<br />

yield pos<br />

In human-speak this means the following: If all but one queen have been placed, go through<br />

all possible positions for the last one, and return the ones that don’t give rise <strong>to</strong> any conflicts.<br />

The num parameter is the number of queens in <strong>to</strong>tal, and the state parameter is the tuple of<br />

positions for the previous queens. For example, let’s say you have four queens, and that the<br />

first three have been given the positions 1, 3, and 0, respectively, as shown in Figure 9-1. (Pay<br />

no attention <strong>to</strong> the white queen at this point.)<br />

Figure 9-1. Placing four queens on a 4×4 board<br />

As you can see in the figure, each queen gets a (horizontal) row, and their positions are<br />

numbered across the <strong>to</strong>p (beginning with zero, as is normal in <strong>Python</strong>):<br />

>>> list(queens(4, (1,3,0)))<br />

[2]<br />

It works like a charm. Using list simply forces the genera<strong>to</strong>r <strong>to</strong> yield all of its values. In this<br />

case, only one position qualifies. The white queen has been put in this position in Figure 9-1.<br />

(Note that color has no special significance and is not part of the program.)<br />

The Recursive Case<br />

Now, let’s turn <strong>to</strong> the recursive part of the solution. When you have your base case covered, the<br />

recursive case may correctly assume (by induction) that all results from lower levels (the queens<br />

with higher numbers) are correct. So what you have <strong>to</strong> do is add an else clause <strong>to</strong> the if statement<br />

in the previous implementation of the queens function.

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

Saved successfully!

Ooh no, something went wrong!