Good Python generators example?
Robert Oschler
no_replies at fake_email_address.invalid
Sun Apr 20 18:16:35 EDT 2003
"Andrew Koenig" <ark at research.att.com> wrote in message
news:yu99y9243nn1.fsf at europa.research.att.com...
> Robert> Can someone point me to a nice concise Python 2.2 compatible
> Robert> example of the use of generators?
>
> Here's a program that solves the "8 queens" problem--that is, the
> problem of how to place 8 queens on a chessboard so that none of
> them attacks any of the others. It prints all the solutions.
>
> from __future__ import generators
>
> class Queens(object):
> def __init__(self, n):
> assert n >= 0
> self.N = n
> self.board = []
>
> def generate(self):
> if len(self.board) == self.N:
> yield self.board[:]
> else:
> for i in range(self.N):
> if self.safe(i):
> self.board.append(i)
> for i in self.generate():
> yield i
> self.board.pop()
>
> def safe(self, n):
> "Is is safe to append a queen to the board in row n?"
> m = len(self.board)
> for i in range(m):
> b = self.board[i]
> if n == b or b+(m-i) == n or b-(m-i) == n:
> return False
> return True
>
> for i in Queens(8).generate():
> print i
>
>
> --
> Andrew Koenig, ark at research.att.com, http://www.research.att.com/info/ark
Andrew,
Thanks! Interesting choice of examples, last time I solved that problem was
with Prolog. With a stack of Python generators you can pretty well emulate
Prolog backtracking, except for the automatic unbinding of variables.
thx
--
Robert Oschler
Android Technologies, Inc.
http://www.androidtechnologies.com
The home of PowerSell! (tm)
The FrontPage AddIn for Amazon Associates
- "Power Tools for Amazon Associates" (sm)
More information about the Python-list
mailing list