1 from __future__
import generators
4 Let's try a simple generator:
20 "Falling off the end" stops the generator:
23 Traceback (most recent call last):
24 File "<stdin>", line 1, in ?
25 File "<stdin>", line 2, in g
28 "return" also stops the generator:
33 ... yield 2 # never reached
39 Traceback (most recent call last):
40 File "<stdin>", line 1, in ?
41 File "<stdin>", line 3, in f
43 >>> g.next() # once stopped, can't be resumed
44 Traceback (most recent call last):
45 File "<stdin>", line 1, in ?
48 "raise StopIteration" stops the generator too:
52 ... raise StopIteration
53 ... yield 2 # never reached
59 Traceback (most recent call last):
60 File "<stdin>", line 1, in ?
63 Traceback (most recent call last):
64 File "<stdin>", line 1, in ?
67 However, they are not exactly equivalent:
80 ... raise StopIteration
86 This may be surprising at first:
97 Let's create an alternate range() function implemented as a generator:
100 ... for i in range(n):
106 Generators always return to the most recent caller:
110 ... print "creator", r.next()
116 ... print "caller", i
125 Generators can call other generators:
128 ... for i in yrange(n):
136 # The examples from PEP 255.
142 Restriction: A generator cannot be resumed while it is actively
150 Traceback (most recent call last):
152 File "<string>", line 2, in g
153 ValueError: generator already executing
155 Specification: Return
157 Note that return isn't always equivalent to raising StopIteration: the
158 difference lies in how enclosing try/except constructs are treated.
169 because, as in any function, return simply exits, but
173 ... raise StopIteration
179 because StopIteration is captured by a bare "except", as is any
182 Specification: Generators and Exception Propagation
187 ... yield f() # the zero division exception propagates
188 ... yield 42 # and we'll never get here
191 Traceback (most recent call last):
192 File "<stdin>", line 1, in ?
193 File "<stdin>", line 2, in g
194 File "<stdin>", line 2, in f
195 ZeroDivisionError: integer division or modulo by zero
196 >>> k.next() # and the generator cannot be resumed
197 Traceback (most recent call last):
198 File "<stdin>", line 1, in ?
202 Specification: Try/Except/Finally
210 ... yield 3 # never get here
211 ... except ZeroDivisionError:
217 ... yield 7 # the "raise" above stops this
227 [1, 2, 4, 5, 8, 9, 10, 11]
230 Guido's binary tree example.
232 >>> # A binary tree class.
235 ... def __init__(self, label, left=None, right=None):
236 ... self.label = label
238 ... self.right = right
240 ... def __repr__(self, level=0, indent=" "):
241 ... s = level*indent + `self.label`
243 ... s = s + "\\n" + self.left.__repr__(level+1, indent)
245 ... s = s + "\\n" + self.right.__repr__(level+1, indent)
248 ... def __iter__(self):
249 ... return inorder(self)
251 >>> # Create a Tree from a list.
257 ... return Tree(list[i], tree(list[:i]), tree(list[i+1:]))
259 >>> # Show it off: create a tree.
260 >>> t = tree("ABCDEFGHIJKLMNOPQRSTUVWXYZ")
262 >>> # A recursive generator that generates Tree leaves in in-order.
265 ... for x in inorder(t.left):
268 ... for x in inorder(t.right):
271 >>> # Show it off: create a tree.
272 ... t = tree("ABCDEFGHIJKLMNOPQRSTUVWXYZ")
273 ... # Print the nodes of the tree in in-order.
276 A B C D E F G H I J K L M N O P Q R S T U V W X Y Z
278 >>> # A non-recursive generator.
279 >>> def inorder(node):
283 ... stack.append(node)
286 ... while not node.right:
288 ... node = stack.pop()
289 ... except IndexError:
292 ... node = node.right
294 >>> # Exercise the non-recursive generator.
297 A B C D E F G H I J K L M N O P Q R S T U V W X Y Z
301 # Examples from Iterator-List and Python-Dev and c.l.py.
305 The difference between yielding None and returning it.
308 ... for i in range(3):
313 [None, None, None, None]
315 Ensure that explicitly raising StopIteration acts like any other exception
316 in try/except, not like a return.
321 ... raise StopIteration
328 Next one was posted to c.l.py.
331 ... "Generate all combinations of k elements from list x."
338 ... first, rest = x[0], x[1:]
339 ... # A combination does or doesn't contain first.
340 ... # If it does, the remainder is a k-1 comb of rest.
341 ... for c in gcomb(rest, k-1):
342 ... c.insert(0, first)
344 ... # If it doesn't contain first, it's a k comb of rest.
345 ... for c in gcomb(rest, k):
348 >>> seq = range(1, 5)
349 >>> for k in range(len(seq) + 2):
350 ... print "%d-combs of %s:" % (k, seq)
351 ... for c in gcomb(seq, k):
353 0-combs of [1, 2, 3, 4]:
355 1-combs of [1, 2, 3, 4]:
360 2-combs of [1, 2, 3, 4]:
367 3-combs of [1, 2, 3, 4]:
372 4-combs of [1, 2, 3, 4]:
374 5-combs of [1, 2, 3, 4]:
376 From the Iterators list, about the types of these things.
386 >>> [s for s in dir(i) if not s.startswith('_')]
387 ['gi_frame', 'gi_running', 'next']
388 >>> print i.next.__doc__
389 x.next() -> the next value, or raise StopIteration
393 >>> isinstance(i, types.GeneratorType)
396 And more, added later.
402 >>> i.gi_running = 42
403 Traceback (most recent call last):
405 TypeError: readonly attribute
407 ... yield me.gi_running
416 A clever union-find implementation from c.l.py, due to David Eppstein.
417 Sent: Friday, June 29, 2001 12:16 PM
418 To: python-list@python.org
419 Subject: Re: PEP 255: Simple Generators
421 >>> class disjointSet:
422 ... def __init__(self, name):
424 ... self.parent = None
425 ... self.generator = self.generate()
427 ... def generate(self):
428 ... while not self.parent:
430 ... for x in self.parent.generator:
434 ... return self.generator.next()
436 ... def union(self, parent):
438 ... raise ValueError("Sorry, I'm not a root!")
439 ... self.parent = parent
441 ... def __str__(self):
444 >>> names = "ABCDEFGHIJKLM"
445 >>> sets = [disjointSet(name) for name in names]
452 ... print "%s->%s" % (s, s.find()),
454 ... if len(roots) > 1:
455 ... s1 = random.choice(roots)
457 ... s2 = random.choice(roots)
459 ... print "merged", s1, "into", s2
462 A->A B->B C->C D->D E->E F->F G->G H->H I->I J->J K->K L->L M->M
464 A->A B->B C->C D->G E->E F->F G->G H->H I->I J->J K->K L->L M->M
466 A->A B->B C->F D->G E->E F->F G->G H->H I->I J->J K->K L->L M->M
468 A->A B->B C->F D->G E->E F->F G->G H->H I->I J->J K->K L->A M->M
470 A->A B->B C->F D->G E->E F->F G->G H->E I->I J->J K->K L->A M->M
472 A->A B->E C->F D->G E->E F->F G->G H->E I->I J->J K->K L->A M->M
474 A->A B->E C->F D->G E->E F->F G->G H->E I->I J->G K->K L->A M->M
476 A->A B->G C->F D->G E->G F->F G->G H->G I->I J->G K->K L->A M->M
478 A->A B->G C->F D->G E->G F->F G->G H->G I->I J->G K->K L->A M->G
480 A->A B->G C->F D->G E->G F->F G->G H->G I->K J->G K->K L->A M->G
482 A->A B->G C->F D->G E->G F->F G->G H->G I->A J->G K->A L->A M->G
484 A->A B->G C->A D->G E->G F->A G->G H->G I->A J->G K->A L->A M->G
486 A->G B->G C->G D->G E->G F->G G->G H->G I->G J->G K->G L->G M->G
489 # Fun tests (for sufficiently warped notions of "fun").
493 Build up to a recursive Sieve of Eratosthenes generator.
495 >>> def firstn(g, n):
496 ... return [g.next() for i in range(n)]
503 >>> firstn(intsfrom(5), 7)
504 [5, 6, 7, 8, 9, 10, 11]
506 >>> def exclude_multiples(n, ints):
511 >>> firstn(exclude_multiples(3, intsfrom(1)), 6)
515 ... prime = ints.next()
517 ... not_divisible_by_prime = exclude_multiples(prime, ints)
518 ... for p in sieve(not_divisible_by_prime):
521 >>> primes = sieve(intsfrom(2))
522 >>> firstn(primes, 20)
523 [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71]
526 Another famous problem: generate all integers of the form
528 in increasing order, where i,j,k >= 0. Trickier than it may look at first!
529 Try writing it without generators, and correctly, and without generating
530 3 internal results for each result output.
535 >>> firstn(times(10, intsfrom(1)), 10)
536 [10, 20, 30, 40, 50, 60, 70, 80, 90, 100]
553 The following works, but is doing a whale of a lot of redundant work --
554 it's not clear how to get the internal uses of m235 to share a single
555 generator. Note that me_times2 (etc) each need to see every element in the
556 result sequence. So this is an example where lazy lists are more natural
557 (you can look at the head of a lazy list any number of times).
561 ... me_times2 = times(2, m235())
562 ... me_times3 = times(3, m235())
563 ... me_times5 = times(5, m235())
564 ... for i in merge(merge(me_times2,
569 Don't print "too many" of these -- the implementation above is extremely
570 inefficient: each call of m235() leads to 3 recursive calls, and in
571 turn each of those 3 more, and so on, and so on, until we've descended
572 enough levels to satisfy the print stmts. Very odd: when I printed 5
573 lines of results below, this managed to screw up Win98's malloc in "the
574 usual" way, i.e. the heap grew over 4Mb so Win98 started fragmenting
575 address space, and it *looked* like a very slow leak.
578 >>> for i in range(3):
579 ... print firstn(result, 15)
580 [1, 2, 3, 4, 5, 6, 8, 9, 10, 12, 15, 16, 18, 20, 24]
581 [25, 27, 30, 32, 36, 40, 45, 48, 50, 54, 60, 64, 72, 75, 80]
582 [81, 90, 96, 100, 108, 120, 125, 128, 135, 144, 150, 160, 162, 180, 192]
584 Heh. Here's one way to get a shared list, complete with an excruciating
585 namespace renaming trick. The *pretty* part is that the times() and merge()
586 functions can be reused as-is, because they only assume their stream
587 arguments are iterable -- a LazyList is the same as a generator to times().
590 ... def __init__(self, g):
592 ... self.fetch = g.next
594 ... def __getitem__(self, i):
595 ... sofar, fetch = self.sofar, self.fetch
596 ... while i >= len(sofar):
597 ... sofar.append(fetch())
602 ... # Gack: m235 below actually refers to a LazyList.
603 ... me_times2 = times(2, m235)
604 ... me_times3 = times(3, m235)
605 ... me_times5 = times(5, m235)
606 ... for i in merge(merge(me_times2,
611 Print as many of these as you like -- *this* implementation is memory-
614 >>> m235 = LazyList(m235())
615 >>> for i in range(5):
616 ... print [m235[j] for j in range(15*i, 15*(i+1))]
617 [1, 2, 3, 4, 5, 6, 8, 9, 10, 12, 15, 16, 18, 20, 24]
618 [25, 27, 30, 32, 36, 40, 45, 48, 50, 54, 60, 64, 72, 75, 80]
619 [81, 90, 96, 100, 108, 120, 125, 128, 135, 144, 150, 160, 162, 180, 192]
620 [200, 216, 225, 240, 243, 250, 256, 270, 288, 300, 320, 324, 360, 375, 384]
621 [400, 405, 432, 450, 480, 486, 500, 512, 540, 576, 600, 625, 640, 648, 675]
624 Ye olde Fibonacci generator, LazyList style.
626 >>> def fibgen(a, b):
630 ... yield g.next() + h.next()
633 ... g.next() # throw first away
639 ... for s in sum(iter(fib),
640 ... tail(iter(fib))):
643 >>> fib = LazyList(fibgen(1, 2))
644 >>> firstn(iter(fib), 17)
645 [1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597, 2584]
648 # syntax_tests mostly provokes SyntaxErrors. Also fiddling with #if 0
656 Traceback (most recent call last):
658 SyntaxError: 'return' with argument inside generator (<string>, line 2)
663 Traceback (most recent call last):
665 SyntaxError: 'return' with argument inside generator (<string>, line 3)
667 "return None" is not the same as "return" in a generator:
672 Traceback (most recent call last):
674 SyntaxError: 'return' with argument inside generator (<string>, line 3)
687 Traceback (most recent call last):
689 SyntaxError: 'yield' not allowed in a 'try' block with a 'finally' clause (<string>, line 3)
695 ... except ZeroDivisionError:
696 ... yield 666 # bad because *outer* try has finally
701 Traceback (most recent call last):
703 SyntaxError: 'yield' not allowed in a 'try' block with a 'finally' clause (<string>, line 6)
712 ... except ZeroDivisionError:
726 Traceback (most recent call last):
727 SyntaxError: invalid syntax
732 Traceback (most recent call last):
733 SyntaxError: invalid syntax
755 ... except SyntaxError:
761 ... yield 2 # don't blink
782 ... def __init__(self):
800 ... lambda x: x # shouldn't trigger here
803 ... return 2*i # or here
805 ... return 3 # but *this* sucks (line 8)
807 ... yield 2 # because it's a generator
808 Traceback (most recent call last):
809 SyntaxError: 'return' with argument inside generator (<string>, line 8)
812 # conjoin is a simple backtracking generator, named in honor of Icon's
813 # "conjunction" control structure. Pass a list of no-argument functions
814 # that return iterable objects. Easiest to explain by example: assume the
815 # function list [x, y, z] is passed. Then conjoin acts like:
818 # values = [None] * 3
819 # for values[0] in x():
820 # for values[1] in y():
821 # for values[2] in z():
824 # So some 3-lists of values *may* be generated, each time we successfully
825 # get into the innermost loop. If an iterator fails (is exhausted) before
826 # then, it "backtracks" to get the next value from the nearest enclosing
827 # iterator (the one "to the left"), and starts all over again at the next
828 # slot (pumps a fresh iterator). Of course this is most useful when the
829 # iterators have side-effects, so that which values *can* be generated at
830 # each slot depend on the values iterated at previous slots.
834 values
= [None] * len(gs
)
836 def gen(i
, values
=values
):
840 for values
[i
] in gs
[i
]():
847 # That works fine, but recursing a level and checking i against len(gs) for
848 # each item produced is inefficient. By doing manual loop unrolling across
849 # generator boundaries, it's possible to eliminate most of that overhead.
850 # This isn't worth the bother *in general* for generators, but conjoin() is
851 # a core building block for some CPU-intensive generator applications.
858 # Do one loop nest at time recursively, until the # of loop nests
859 # remaining is divisible by 3.
861 def gen(i
, values
=values
):
867 for values
[i
] in gs
[i
]():
875 # Do three loop nests at a time, recursing only if at least three more
876 # remain. Don't call directly: this is an internal optimization for
879 def _gen3(i
, values
=values
):
880 assert i
< n
and (n
-i
) % 3 == 0
881 ip1
, ip2
, ip3
= i
+1, i
+2, i
+3
882 g
, g1
, g2
= gs
[i
: ip3
]
885 # These are the last three, so we can yield values directly.
886 for values
[i
] in g():
887 for values
[ip1
] in g1():
888 for values
[ip2
] in g2():
892 # At least 6 loop nests remain; peel off 3 and recurse for the
894 for values
[i
] in g():
895 for values
[ip1
] in g1():
896 for values
[ip2
] in g2():
903 # And one more approach: For backtracking apps like the Knight's Tour
904 # solver below, the number of backtracking levels can be enormous (one
905 # level per square, for the Knight's Tour, so that e.g. a 100x100 board
906 # needs 10,000 levels). In such cases Python is likely to run out of
907 # stack space due to recursion. So here's a recursion-free version of
909 # NOTE WELL: This allows large problems to be solved with only trivial
910 # demands on stack space. Without explicitly resumable generators, this is
911 # much harder to achieve. OTOH, this is much slower (up to a factor of 2)
912 # than the fancy unrolled recursive conjoin.
914 def flat_conjoin(gs
): # rename to conjoin to run tests with this instead
918 _StopIteration
= StopIteration # make local because caught a *lot*
924 it
= iters
[i
] = gs
[i
]().next
927 except _StopIteration
:
933 # Backtrack until an older iterator can be resumed.
937 values
[i
] = iters
[i
]()
938 # Success! Start fresh at next level.
941 except _StopIteration
:
942 # Continue backtracking.
948 # A conjoin-based N-Queens solver.
951 def __init__(self
, n
):
955 # Assign a unique int to each column and diagonal.
956 # columns: n of those, range(n).
957 # NW-SE diagonals: 2n-1 of these, i-j unique and invariant along
958 # each, smallest i-j is 0-(n-1) = 1-n, so add n-1 to shift to 0-
960 # NE-SW diagonals: 2n-1 of these, i+j unique and invariant along
961 # each, smallest i+j is 0, largest is 2n-2.
963 # For each square, compute a bit vector of the columns and
964 # diagonals it covers, and for each row compute a function that
965 # generates the possiblities for the columns in that row.
966 self
.rowgenerators
= []
968 rowuses
= [(1L << j
) |
# column ordinal
969 (1L << (n
+ i
-j
+ n
-1)) |
# NW-SE ordinal
970 (1L << (n
+ 2*n
-1 + i
+j
)) # NE-SW ordinal
973 def rowgen(rowuses
=rowuses
):
976 if uses
& self
.used
== 0:
981 self
.rowgenerators
.append(rowgen
)
983 # Generate solutions.
986 for row2col
in conjoin(self
.rowgenerators
):
989 def printsolution(self
, row2col
):
991 assert n
== len(row2col
)
995 squares
= [" " for j
in range(n
)]
996 squares
[row2col
[i
]] = "Q"
997 print "|" + "|".join(squares
) + "|"
1000 # A conjoin-based Knight's Tour solver. This is pretty sophisticated
1001 # (e.g., when used with flat_conjoin above, and passing hard=1 to the
1002 # constructor, a 200x200 Knight's Tour was found quickly -- note that we're
1003 # creating 10s of thousands of generators then!), and is lengthy.
1006 def __init__(self
, m
, n
, hard
=0):
1007 self
.m
, self
.n
= m
, n
1009 # solve() will set up succs[i] to be a list of square #i's
1011 succs
= self
.succs
= []
1013 # Remove i0 from each of its successor's successor lists, i.e.
1014 # successors can't go back to i0 again. Return 0 if we can
1015 # detect this makes a solution impossible, else return 1.
1017 def remove_from_successors(i0
, len=len):
1018 # If we remove all exits from a free square, we're dead:
1019 # even if we move to it next, we can't leave it again.
1020 # If we create a square with one exit, we must visit it next;
1021 # else somebody else will have to visit it, and since there's
1022 # only one adjacent, there won't be a way to leave it again.
1023 # Finelly, if we create more than one free square with a
1024 # single exit, we can only move to one of them next, leaving
1025 # the other one a dead end.
1035 return ne0
== 0 and ne1
< 2
1037 # Put i0 back in each of its successor's successor lists.
1039 def add_to_successors(i0
):
1043 # Generate the first move.
1048 # Since we're looking for a cycle, it doesn't matter where we
1049 # start. Starting in a corner makes the 2nd move easy.
1050 corner
= self
.coords2index(0, 0)
1051 remove_from_successors(corner
)
1052 self
.lastij
= corner
1054 add_to_successors(corner
)
1056 # Generate the second moves.
1058 corner
= self
.coords2index(0, 0)
1059 assert self
.lastij
== corner
# i.e., we started in the corner
1062 assert len(succs
[corner
]) == 2
1063 assert self
.coords2index(1, 2) in succs
[corner
]
1064 assert self
.coords2index(2, 1) in succs
[corner
]
1065 # Only two choices. Whichever we pick, the other must be the
1066 # square picked on move m*n, as it's the only way to get back
1067 # to (0, 0). Save its index in self.final so that moves before
1068 # the last know it must be kept free.
1069 for i
, j
in (1, 2), (2, 1):
1070 this
= self
.coords2index(i
, j
)
1071 final
= self
.coords2index(3-i
, 3-j
)
1074 remove_from_successors(this
)
1075 succs
[final
].append(corner
)
1078 succs
[final
].remove(corner
)
1079 add_to_successors(this
)
1081 # Generate moves 3 thru m*n-1.
1082 def advance(len=len):
1083 # If some successor has only one exit, must take it.
1084 # Else favor successors with fewer exits.
1086 for i
in succs
[self
.lastij
]:
1088 assert e
> 0, "else remove_from_successors() pruning flawed"
1090 candidates
= [(e
, i
)]
1092 candidates
.append((e
, i
))
1096 for e
, i
in candidates
:
1098 if remove_from_successors(i
):
1101 add_to_successors(i
)
1103 # Generate moves 3 thru m*n-1. Alternative version using a
1104 # stronger (but more expensive) heuristic to order successors.
1105 # Since the # of backtracking levels is m*n, a poor move early on
1106 # can take eons to undo. Smallest square board for which this
1107 # matters a lot is 52x52.
1108 def advance_hard(vmid
=(m
-1)/2.0, hmid
=(n
-1)/2.0, len=len):
1109 # If some successor has only one exit, must take it.
1110 # Else favor successors with fewer exits.
1111 # Break ties via max distance from board centerpoint (favor
1112 # corners and edges whenever possible).
1114 for i
in succs
[self
.lastij
]:
1116 assert e
> 0, "else remove_from_successors() pruning flawed"
1118 candidates
= [(e
, 0, i
)]
1120 i1
, j1
= self
.index2coords(i
)
1121 d
= (i1
- vmid
)**2 + (j1
- hmid
)**2
1122 candidates
.append((e
, -d
, i
))
1126 for e
, d
, i
in candidates
:
1128 if remove_from_successors(i
):
1131 add_to_successors(i
)
1133 # Generate the last move.
1135 assert self
.final
in succs
[self
.lastij
]
1139 self
.squaregenerators
= [first
]
1141 self
.squaregenerators
= [first
, second
] + \
1142 [hard
and advance_hard
or advance
] * (m
*n
- 3) + \
1145 def coords2index(self
, i
, j
):
1146 assert 0 <= i
< self
.m
1147 assert 0 <= j
< self
.n
1148 return i
* self
.n
+ j
1150 def index2coords(self
, index
):
1151 assert 0 <= index
< self
.m
* self
.n
1152 return divmod(index
, self
.n
)
1154 def _init_board(self
):
1157 m
, n
= self
.m
, self
.n
1158 c2i
= self
.coords2index
1160 offsets
= [( 1, 2), ( 2, 1), ( 2, -1), ( 1, -2),
1161 (-1, -2), (-2, -1), (-2, 1), (-1, 2)]
1165 s
= [c2i(i
+io
, j
+jo
) for io
, jo
in offsets
1166 if 0 <= i
+io
< m
and
1170 # Generate solutions.
1173 for x
in conjoin(self
.squaregenerators
):
1176 def printsolution(self
, x
):
1177 m
, n
= self
.m
, self
.n
1178 assert len(x
) == m
*n
1180 format
= "%" + str(w
) + "d"
1182 squares
= [[None] * n
for i
in range(m
)]
1185 i1
, j1
= self
.index2coords(i
)
1186 squares
[i1
][j1
] = format
% k
1189 sep
= "+" + ("-" * w
+ "+") * n
1193 print "|" + "|".join(row
) + "|"
1198 Generate the 3-bit binary numbers in order. This illustrates dumbest-
1199 possible use of conjoin, just to generate the full cross-product.
1201 >>> for c in conjoin([lambda: iter((0, 1))] * 3):
1212 For efficiency in typical backtracking apps, conjoin() yields the same list
1213 object each time. So if you want to save away a full account of its
1214 generated sequence, you need to copy its results.
1216 >>> def gencopy(iterator):
1217 ... for x in iterator:
1220 >>> for n in range(10):
1221 ... all = list(gencopy(conjoin([lambda: iter((0, 1))] * n)))
1222 ... print n, len(all), all[0] == [0] * n, all[-1] == [1] * n
1234 And run an 8-queens solver.
1239 >>> for row2col in q.solve():
1241 ... if count <= LIMIT:
1242 ... print "Solution", count
1243 ... q.printsolution(row2col)
1281 >>> print count, "solutions in all."
1282 92 solutions in all.
1284 And run a Knight's Tour on a 10x10 board. Note that there are about
1285 20,000 solutions even on a 6x6 board, so don't dare run this to exhaustion.
1287 >>> k = Knights(10, 10)
1290 >>> for x in k.solve():
1292 ... if count <= LIMIT:
1293 ... print "Solution", count
1294 ... k.printsolution(x)
1298 +---+---+---+---+---+---+---+---+---+---+
1299 | 1| 58| 27| 34| 3| 40| 29| 10| 5| 8|
1300 +---+---+---+---+---+---+---+---+---+---+
1301 | 26| 35| 2| 57| 28| 33| 4| 7| 30| 11|
1302 +---+---+---+---+---+---+---+---+---+---+
1303 | 59|100| 73| 36| 41| 56| 39| 32| 9| 6|
1304 +---+---+---+---+---+---+---+---+---+---+
1305 | 74| 25| 60| 55| 72| 37| 42| 49| 12| 31|
1306 +---+---+---+---+---+---+---+---+---+---+
1307 | 61| 86| 99| 76| 63| 52| 47| 38| 43| 50|
1308 +---+---+---+---+---+---+---+---+---+---+
1309 | 24| 75| 62| 85| 54| 71| 64| 51| 48| 13|
1310 +---+---+---+---+---+---+---+---+---+---+
1311 | 87| 98| 91| 80| 77| 84| 53| 46| 65| 44|
1312 +---+---+---+---+---+---+---+---+---+---+
1313 | 90| 23| 88| 95| 70| 79| 68| 83| 14| 17|
1314 +---+---+---+---+---+---+---+---+---+---+
1315 | 97| 92| 21| 78| 81| 94| 19| 16| 45| 66|
1316 +---+---+---+---+---+---+---+---+---+---+
1317 | 22| 89| 96| 93| 20| 69| 82| 67| 18| 15|
1318 +---+---+---+---+---+---+---+---+---+---+
1320 +---+---+---+---+---+---+---+---+---+---+
1321 | 1| 58| 27| 34| 3| 40| 29| 10| 5| 8|
1322 +---+---+---+---+---+---+---+---+---+---+
1323 | 26| 35| 2| 57| 28| 33| 4| 7| 30| 11|
1324 +---+---+---+---+---+---+---+---+---+---+
1325 | 59|100| 73| 36| 41| 56| 39| 32| 9| 6|
1326 +---+---+---+---+---+---+---+---+---+---+
1327 | 74| 25| 60| 55| 72| 37| 42| 49| 12| 31|
1328 +---+---+---+---+---+---+---+---+---+---+
1329 | 61| 86| 99| 76| 63| 52| 47| 38| 43| 50|
1330 +---+---+---+---+---+---+---+---+---+---+
1331 | 24| 75| 62| 85| 54| 71| 64| 51| 48| 13|
1332 +---+---+---+---+---+---+---+---+---+---+
1333 | 87| 98| 89| 80| 77| 84| 53| 46| 65| 44|
1334 +---+---+---+---+---+---+---+---+---+---+
1335 | 90| 23| 92| 95| 70| 79| 68| 83| 14| 17|
1336 +---+---+---+---+---+---+---+---+---+---+
1337 | 97| 88| 21| 78| 81| 94| 19| 16| 45| 66|
1338 +---+---+---+---+---+---+---+---+---+---+
1339 | 22| 91| 96| 93| 20| 69| 82| 67| 18| 15|
1340 +---+---+---+---+---+---+---+---+---+---+
1343 __test__
= {"tut": tutorial_tests
,
1345 "email": email_tests
,
1347 "syntax": syntax_tests
,
1348 "conjoin": conjoin_tests
}
1350 # Magic test name that regrtest.py invokes *after* importing this module.
1351 # This worms around a bootstrap problem.
1352 # Note that doctest and regrtest both look in sys.argv for a "-v" argument,
1353 # so this works as expected in both ways of running regrtest.
1354 def test_main(verbose
=None):
1355 import doctest
, test_support
, test_generators
1356 if 0: # change to 1 to run forever (to check for leaks)
1358 doctest
.master
= None
1359 test_support
.run_doctest(test_generators
, verbose
)
1362 test_support
.run_doctest(test_generators
, verbose
)
1364 # This part isn't needed for regrtest, but for running the test directly.
1365 if __name__
== "__main__":