blob: 17523ba71c92c1688ed69429bb59af1d9c917beb [file] [log] [blame]
Tim Peters6ba5f792001-06-23 20:45:43 +00001tutorial_tests = """
Tim Peters1def3512001-06-23 20:27:04 +00002Let's try a simple generator:
3
4 >>> def f():
5 ... yield 1
6 ... yield 2
7
Tim Petersb9e9ff12001-06-24 03:44:52 +00008 >>> for i in f():
9 ... print i
10 1
11 2
Tim Peters1def3512001-06-23 20:27:04 +000012 >>> g = f()
13 >>> g.next()
14 1
15 >>> g.next()
16 2
Tim Petersea2e97a2001-06-24 07:10:02 +000017
Tim Peters2106ef02001-06-25 01:30:12 +000018"Falling off the end" stops the generator:
Tim Petersea2e97a2001-06-24 07:10:02 +000019
Tim Peters1def3512001-06-23 20:27:04 +000020 >>> g.next()
21 Traceback (most recent call last):
22 File "<stdin>", line 1, in ?
23 File "<stdin>", line 2, in g
24 StopIteration
25
Tim Petersea2e97a2001-06-24 07:10:02 +000026"return" also stops the generator:
Tim Peters1def3512001-06-23 20:27:04 +000027
28 >>> def f():
29 ... yield 1
30 ... return
31 ... yield 2 # never reached
32 ...
33 >>> g = f()
34 >>> g.next()
35 1
36 >>> g.next()
37 Traceback (most recent call last):
38 File "<stdin>", line 1, in ?
39 File "<stdin>", line 3, in f
40 StopIteration
41 >>> g.next() # once stopped, can't be resumed
42 Traceback (most recent call last):
43 File "<stdin>", line 1, in ?
44 StopIteration
45
46"raise StopIteration" stops the generator too:
47
48 >>> def f():
49 ... yield 1
Tim Peters34463652001-07-12 22:43:41 +000050 ... raise StopIteration
Tim Peters1def3512001-06-23 20:27:04 +000051 ... yield 2 # never reached
52 ...
53 >>> g = f()
54 >>> g.next()
55 1
56 >>> g.next()
57 Traceback (most recent call last):
58 File "<stdin>", line 1, in ?
59 StopIteration
60 >>> g.next()
61 Traceback (most recent call last):
62 File "<stdin>", line 1, in ?
63 StopIteration
64
65However, they are not exactly equivalent:
66
67 >>> def g1():
68 ... try:
69 ... return
70 ... except:
71 ... yield 1
72 ...
73 >>> list(g1())
74 []
75
76 >>> def g2():
77 ... try:
78 ... raise StopIteration
79 ... except:
80 ... yield 42
81 >>> print list(g2())
82 [42]
83
84This may be surprising at first:
85
86 >>> def g3():
87 ... try:
88 ... return
89 ... finally:
90 ... yield 1
91 ...
92 >>> list(g3())
93 [1]
94
95Let's create an alternate range() function implemented as a generator:
96
97 >>> def yrange(n):
98 ... for i in range(n):
99 ... yield i
100 ...
101 >>> list(yrange(5))
102 [0, 1, 2, 3, 4]
103
104Generators always return to the most recent caller:
105
106 >>> def creator():
107 ... r = yrange(5)
108 ... print "creator", r.next()
109 ... return r
110 ...
111 >>> def caller():
112 ... r = creator()
113 ... for i in r:
114 ... print "caller", i
115 ...
116 >>> caller()
117 creator 0
118 caller 1
119 caller 2
120 caller 3
121 caller 4
122
123Generators can call other generators:
124
125 >>> def zrange(n):
126 ... for i in yrange(n):
127 ... yield i
128 ...
129 >>> list(zrange(5))
130 [0, 1, 2, 3, 4]
131
132"""
133
Tim Peters6ba5f792001-06-23 20:45:43 +0000134# The examples from PEP 255.
135
136pep_tests = """
137
Tim Peterse5614632001-08-15 04:41:19 +0000138Specification: Yield
139
140 Restriction: A generator cannot be resumed while it is actively
141 running:
142
143 >>> def g():
144 ... i = me.next()
145 ... yield i
146 >>> me = g()
147 >>> me.next()
148 Traceback (most recent call last):
149 ...
150 File "<string>", line 2, in g
151 ValueError: generator already executing
152
Tim Peters6ba5f792001-06-23 20:45:43 +0000153Specification: Return
154
155 Note that return isn't always equivalent to raising StopIteration: the
156 difference lies in how enclosing try/except constructs are treated.
157 For example,
158
159 >>> def f1():
160 ... try:
161 ... return
162 ... except:
163 ... yield 1
164 >>> print list(f1())
165 []
166
167 because, as in any function, return simply exits, but
168
169 >>> def f2():
170 ... try:
171 ... raise StopIteration
172 ... except:
173 ... yield 42
174 >>> print list(f2())
175 [42]
176
177 because StopIteration is captured by a bare "except", as is any
178 exception.
179
180Specification: Generators and Exception Propagation
181
182 >>> def f():
Tim Peters3caca232001-12-06 06:23:26 +0000183 ... return 1//0
Tim Peters6ba5f792001-06-23 20:45:43 +0000184 >>> def g():
185 ... yield f() # the zero division exception propagates
186 ... yield 42 # and we'll never get here
187 >>> k = g()
188 >>> k.next()
189 Traceback (most recent call last):
190 File "<stdin>", line 1, in ?
191 File "<stdin>", line 2, in g
192 File "<stdin>", line 2, in f
193 ZeroDivisionError: integer division or modulo by zero
194 >>> k.next() # and the generator cannot be resumed
195 Traceback (most recent call last):
196 File "<stdin>", line 1, in ?
197 StopIteration
198 >>>
199
200Specification: Try/Except/Finally
201
202 >>> def f():
203 ... try:
204 ... yield 1
205 ... try:
206 ... yield 2
Tim Peters3caca232001-12-06 06:23:26 +0000207 ... 1//0
Tim Peters6ba5f792001-06-23 20:45:43 +0000208 ... yield 3 # never get here
209 ... except ZeroDivisionError:
210 ... yield 4
211 ... yield 5
212 ... raise
213 ... except:
214 ... yield 6
215 ... yield 7 # the "raise" above stops this
216 ... except:
217 ... yield 8
218 ... yield 9
219 ... try:
220 ... x = 12
221 ... finally:
222 ... yield 10
223 ... yield 11
224 >>> print list(f())
225 [1, 2, 4, 5, 8, 9, 10, 11]
226 >>>
227
Tim Peters6ba5f792001-06-23 20:45:43 +0000228Guido's binary tree example.
229
230 >>> # A binary tree class.
231 >>> class Tree:
232 ...
233 ... def __init__(self, label, left=None, right=None):
234 ... self.label = label
235 ... self.left = left
236 ... self.right = right
237 ...
238 ... def __repr__(self, level=0, indent=" "):
239 ... s = level*indent + `self.label`
240 ... if self.left:
241 ... s = s + "\\n" + self.left.__repr__(level+1, indent)
242 ... if self.right:
243 ... s = s + "\\n" + self.right.__repr__(level+1, indent)
244 ... return s
245 ...
246 ... def __iter__(self):
247 ... return inorder(self)
248
249 >>> # Create a Tree from a list.
250 >>> def tree(list):
251 ... n = len(list)
252 ... if n == 0:
253 ... return []
Tim Peters3caca232001-12-06 06:23:26 +0000254 ... i = n // 2
Tim Peters6ba5f792001-06-23 20:45:43 +0000255 ... return Tree(list[i], tree(list[:i]), tree(list[i+1:]))
256
257 >>> # Show it off: create a tree.
258 >>> t = tree("ABCDEFGHIJKLMNOPQRSTUVWXYZ")
259
Tim Petersd674e172002-03-10 07:59:13 +0000260 >>> # A recursive generator that generates Tree labels in in-order.
Tim Peters6ba5f792001-06-23 20:45:43 +0000261 >>> def inorder(t):
262 ... if t:
263 ... for x in inorder(t.left):
264 ... yield x
265 ... yield t.label
266 ... for x in inorder(t.right):
267 ... yield x
268
269 >>> # Show it off: create a tree.
270 ... t = tree("ABCDEFGHIJKLMNOPQRSTUVWXYZ")
271 ... # Print the nodes of the tree in in-order.
272 ... for x in t:
273 ... print x,
274 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
275
276 >>> # A non-recursive generator.
277 >>> def inorder(node):
278 ... stack = []
279 ... while node:
280 ... while node.left:
281 ... stack.append(node)
282 ... node = node.left
283 ... yield node.label
284 ... while not node.right:
285 ... try:
286 ... node = stack.pop()
287 ... except IndexError:
288 ... return
289 ... yield node.label
290 ... node = node.right
291
292 >>> # Exercise the non-recursive generator.
293 >>> for x in t:
294 ... print x,
295 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
296
297"""
298
Tim Petersb2bc6a92001-06-24 10:14:27 +0000299# Examples from Iterator-List and Python-Dev and c.l.py.
Tim Peters6ba5f792001-06-23 20:45:43 +0000300
301email_tests = """
302
303The difference between yielding None and returning it.
304
305>>> def g():
306... for i in range(3):
307... yield None
308... yield None
309... return
310>>> list(g())
311[None, None, None, None]
312
313Ensure that explicitly raising StopIteration acts like any other exception
314in try/except, not like a return.
315
316>>> def g():
317... yield 1
318... try:
319... raise StopIteration
320... except:
321... yield 2
322... yield 3
323>>> list(g())
324[1, 2, 3]
Tim Petersb9e9ff12001-06-24 03:44:52 +0000325
Tim Petersb2bc6a92001-06-24 10:14:27 +0000326Next one was posted to c.l.py.
327
328>>> def gcomb(x, k):
329... "Generate all combinations of k elements from list x."
330...
331... if k > len(x):
332... return
333... if k == 0:
334... yield []
335... else:
336... first, rest = x[0], x[1:]
337... # A combination does or doesn't contain first.
338... # If it does, the remainder is a k-1 comb of rest.
339... for c in gcomb(rest, k-1):
340... c.insert(0, first)
341... yield c
342... # If it doesn't contain first, it's a k comb of rest.
343... for c in gcomb(rest, k):
344... yield c
345
346>>> seq = range(1, 5)
347>>> for k in range(len(seq) + 2):
348... print "%d-combs of %s:" % (k, seq)
349... for c in gcomb(seq, k):
350... print " ", c
3510-combs of [1, 2, 3, 4]:
352 []
3531-combs of [1, 2, 3, 4]:
354 [1]
355 [2]
356 [3]
357 [4]
3582-combs of [1, 2, 3, 4]:
359 [1, 2]
360 [1, 3]
361 [1, 4]
362 [2, 3]
363 [2, 4]
364 [3, 4]
3653-combs of [1, 2, 3, 4]:
366 [1, 2, 3]
367 [1, 2, 4]
368 [1, 3, 4]
369 [2, 3, 4]
3704-combs of [1, 2, 3, 4]:
371 [1, 2, 3, 4]
3725-combs of [1, 2, 3, 4]:
Tim Peters3e7b1a02001-06-25 19:46:25 +0000373
Tim Peterse77f2e22001-06-26 22:24:51 +0000374From the Iterators list, about the types of these things.
Tim Peters3e7b1a02001-06-25 19:46:25 +0000375
376>>> def g():
377... yield 1
378...
379>>> type(g)
380<type 'function'>
381>>> i = g()
382>>> type(i)
383<type 'generator'>
Tim Peters5d2b77c2001-09-03 05:47:38 +0000384>>> [s for s in dir(i) if not s.startswith('_')]
Tim Peterse77f2e22001-06-26 22:24:51 +0000385['gi_frame', 'gi_running', 'next']
Tim Peters3e7b1a02001-06-25 19:46:25 +0000386>>> print i.next.__doc__
Tim Peters6d6c1a32001-08-02 04:15:00 +0000387x.next() -> the next value, or raise StopIteration
Tim Peters3e7b1a02001-06-25 19:46:25 +0000388>>> iter(i) is i
Guido van Rossum77f6a652002-04-03 22:41:51 +0000389True
Tim Peters3e7b1a02001-06-25 19:46:25 +0000390>>> import types
391>>> isinstance(i, types.GeneratorType)
Guido van Rossum77f6a652002-04-03 22:41:51 +0000392True
Tim Peterse77f2e22001-06-26 22:24:51 +0000393
394And more, added later.
395
396>>> i.gi_running
3970
398>>> type(i.gi_frame)
399<type 'frame'>
400>>> i.gi_running = 42
401Traceback (most recent call last):
402 ...
Guido van Rossum61cf7802001-08-10 21:25:24 +0000403TypeError: readonly attribute
Tim Peterse77f2e22001-06-26 22:24:51 +0000404>>> def g():
405... yield me.gi_running
406>>> me = g()
407>>> me.gi_running
4080
409>>> me.next()
4101
411>>> me.gi_running
4120
Tim Peters35302662001-07-02 01:38:33 +0000413
414A clever union-find implementation from c.l.py, due to David Eppstein.
415Sent: Friday, June 29, 2001 12:16 PM
416To: python-list@python.org
417Subject: Re: PEP 255: Simple Generators
418
419>>> class disjointSet:
420... def __init__(self, name):
421... self.name = name
422... self.parent = None
423... self.generator = self.generate()
424...
425... def generate(self):
426... while not self.parent:
427... yield self
428... for x in self.parent.generator:
429... yield x
430...
431... def find(self):
432... return self.generator.next()
433...
434... def union(self, parent):
435... if self.parent:
436... raise ValueError("Sorry, I'm not a root!")
437... self.parent = parent
438...
439... def __str__(self):
440... return self.name
Tim Peters35302662001-07-02 01:38:33 +0000441
442>>> names = "ABCDEFGHIJKLM"
443>>> sets = [disjointSet(name) for name in names]
444>>> roots = sets[:]
445
446>>> import random
447>>> random.seed(42)
448>>> while 1:
449... for s in sets:
450... print "%s->%s" % (s, s.find()),
451... print
452... if len(roots) > 1:
453... s1 = random.choice(roots)
454... roots.remove(s1)
455... s2 = random.choice(roots)
456... s1.union(s2)
457... print "merged", s1, "into", s2
458... else:
459... break
460A->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
461merged D into G
462A->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
463merged C into F
464A->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
465merged L into A
466A->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
467merged H into E
468A->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
469merged B into E
470A->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
471merged J into G
472A->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
473merged E into G
474A->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
475merged M into G
476A->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
477merged I into K
478A->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
479merged K into A
480A->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
481merged F into A
482A->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
483merged A into G
484A->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
Tim Peters6ba5f792001-06-23 20:45:43 +0000485"""
486
Tim Peters0f9da0a2001-06-23 21:01:47 +0000487# Fun tests (for sufficiently warped notions of "fun").
488
489fun_tests = """
490
491Build up to a recursive Sieve of Eratosthenes generator.
492
493>>> def firstn(g, n):
494... return [g.next() for i in range(n)]
495
496>>> def intsfrom(i):
497... while 1:
498... yield i
499... i += 1
500
501>>> firstn(intsfrom(5), 7)
502[5, 6, 7, 8, 9, 10, 11]
503
504>>> def exclude_multiples(n, ints):
505... for i in ints:
506... if i % n:
507... yield i
508
509>>> firstn(exclude_multiples(3, intsfrom(1)), 6)
510[1, 2, 4, 5, 7, 8]
511
512>>> def sieve(ints):
513... prime = ints.next()
514... yield prime
515... not_divisible_by_prime = exclude_multiples(prime, ints)
516... for p in sieve(not_divisible_by_prime):
517... yield p
518
519>>> primes = sieve(intsfrom(2))
520>>> firstn(primes, 20)
521[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71]
Tim Petersb9e9ff12001-06-24 03:44:52 +0000522
Tim Petersf6ed0742001-06-27 07:17:57 +0000523
Tim Petersb9e9ff12001-06-24 03:44:52 +0000524Another famous problem: generate all integers of the form
525 2**i * 3**j * 5**k
526in increasing order, where i,j,k >= 0. Trickier than it may look at first!
527Try writing it without generators, and correctly, and without generating
5283 internal results for each result output.
529
530>>> def times(n, g):
531... for i in g:
532... yield n * i
533>>> firstn(times(10, intsfrom(1)), 10)
534[10, 20, 30, 40, 50, 60, 70, 80, 90, 100]
535
536>>> def merge(g, h):
537... ng = g.next()
538... nh = h.next()
539... while 1:
540... if ng < nh:
541... yield ng
542... ng = g.next()
543... elif ng > nh:
544... yield nh
545... nh = h.next()
546... else:
547... yield ng
548... ng = g.next()
549... nh = h.next()
550
Tim Petersf6ed0742001-06-27 07:17:57 +0000551The following works, but is doing a whale of a lot of redundant work --
552it's not clear how to get the internal uses of m235 to share a single
553generator. Note that me_times2 (etc) each need to see every element in the
554result sequence. So this is an example where lazy lists are more natural
555(you can look at the head of a lazy list any number of times).
Tim Petersb9e9ff12001-06-24 03:44:52 +0000556
557>>> def m235():
558... yield 1
559... me_times2 = times(2, m235())
560... me_times3 = times(3, m235())
561... me_times5 = times(5, m235())
562... for i in merge(merge(me_times2,
563... me_times3),
564... me_times5):
565... yield i
566
Tim Petersf6ed0742001-06-27 07:17:57 +0000567Don't print "too many" of these -- the implementation above is extremely
568inefficient: each call of m235() leads to 3 recursive calls, and in
569turn each of those 3 more, and so on, and so on, until we've descended
570enough levels to satisfy the print stmts. Very odd: when I printed 5
571lines of results below, this managed to screw up Win98's malloc in "the
572usual" way, i.e. the heap grew over 4Mb so Win98 started fragmenting
573address space, and it *looked* like a very slow leak.
574
Tim Petersb9e9ff12001-06-24 03:44:52 +0000575>>> result = m235()
Tim Petersf6ed0742001-06-27 07:17:57 +0000576>>> for i in range(3):
Tim Petersb9e9ff12001-06-24 03:44:52 +0000577... print firstn(result, 15)
578[1, 2, 3, 4, 5, 6, 8, 9, 10, 12, 15, 16, 18, 20, 24]
579[25, 27, 30, 32, 36, 40, 45, 48, 50, 54, 60, 64, 72, 75, 80]
580[81, 90, 96, 100, 108, 120, 125, 128, 135, 144, 150, 160, 162, 180, 192]
Tim Petersee309272001-06-24 05:47:06 +0000581
582Heh. Here's one way to get a shared list, complete with an excruciating
583namespace renaming trick. The *pretty* part is that the times() and merge()
584functions can be reused as-is, because they only assume their stream
585arguments are iterable -- a LazyList is the same as a generator to times().
586
587>>> class LazyList:
588... def __init__(self, g):
589... self.sofar = []
590... self.fetch = g.next
591...
592... def __getitem__(self, i):
593... sofar, fetch = self.sofar, self.fetch
594... while i >= len(sofar):
595... sofar.append(fetch())
596... return sofar[i]
597
598>>> def m235():
599... yield 1
Tim Petersea2e97a2001-06-24 07:10:02 +0000600... # Gack: m235 below actually refers to a LazyList.
Tim Petersee309272001-06-24 05:47:06 +0000601... me_times2 = times(2, m235)
602... me_times3 = times(3, m235)
603... me_times5 = times(5, m235)
604... for i in merge(merge(me_times2,
605... me_times3),
606... me_times5):
607... yield i
608
Tim Petersf6ed0742001-06-27 07:17:57 +0000609Print as many of these as you like -- *this* implementation is memory-
Neil Schemenauerb20e9db2001-07-12 13:26:41 +0000610efficient.
Tim Petersf6ed0742001-06-27 07:17:57 +0000611
Tim Petersee309272001-06-24 05:47:06 +0000612>>> m235 = LazyList(m235())
613>>> for i in range(5):
614... print [m235[j] for j in range(15*i, 15*(i+1))]
615[1, 2, 3, 4, 5, 6, 8, 9, 10, 12, 15, 16, 18, 20, 24]
616[25, 27, 30, 32, 36, 40, 45, 48, 50, 54, 60, 64, 72, 75, 80]
617[81, 90, 96, 100, 108, 120, 125, 128, 135, 144, 150, 160, 162, 180, 192]
618[200, 216, 225, 240, 243, 250, 256, 270, 288, 300, 320, 324, 360, 375, 384]
619[400, 405, 432, 450, 480, 486, 500, 512, 540, 576, 600, 625, 640, 648, 675]
Tim Petersf6ed0742001-06-27 07:17:57 +0000620
Tim Petersf6ed0742001-06-27 07:17:57 +0000621
622Ye olde Fibonacci generator, LazyList style.
623
624>>> def fibgen(a, b):
625...
626... def sum(g, h):
627... while 1:
628... yield g.next() + h.next()
629...
630... def tail(g):
631... g.next() # throw first away
632... for x in g:
633... yield x
634...
635... yield a
636... yield b
637... for s in sum(iter(fib),
638... tail(iter(fib))):
639... yield s
640
641>>> fib = LazyList(fibgen(1, 2))
642>>> firstn(iter(fib), 17)
643[1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597, 2584]
Tim Peters0f9da0a2001-06-23 21:01:47 +0000644"""
645
Tim Petersb6c3cea2001-06-26 03:36:28 +0000646# syntax_tests mostly provokes SyntaxErrors. Also fiddling with #if 0
647# hackery.
Tim Petersee309272001-06-24 05:47:06 +0000648
Tim Petersea2e97a2001-06-24 07:10:02 +0000649syntax_tests = """
650
651>>> def f():
652... return 22
653... yield 1
654Traceback (most recent call last):
655 ...
656SyntaxError: 'return' with argument inside generator (<string>, line 2)
657
658>>> def f():
659... yield 1
660... return 22
661Traceback (most recent call last):
662 ...
663SyntaxError: 'return' with argument inside generator (<string>, line 3)
664
665"return None" is not the same as "return" in a generator:
666
667>>> def f():
668... yield 1
669... return None
670Traceback (most recent call last):
671 ...
672SyntaxError: 'return' with argument inside generator (<string>, line 3)
673
674This one is fine:
675
676>>> def f():
677... yield 1
678... return
679
680>>> def f():
681... try:
682... yield 1
683... finally:
684... pass
685Traceback (most recent call last):
686 ...
687SyntaxError: 'yield' not allowed in a 'try' block with a 'finally' clause (<string>, line 3)
688
689>>> def f():
690... try:
691... try:
Tim Peters3caca232001-12-06 06:23:26 +0000692... 1//0
Tim Petersea2e97a2001-06-24 07:10:02 +0000693... except ZeroDivisionError:
694... yield 666 # bad because *outer* try has finally
695... except:
696... pass
697... finally:
698... pass
699Traceback (most recent call last):
700 ...
701SyntaxError: 'yield' not allowed in a 'try' block with a 'finally' clause (<string>, line 6)
702
703But this is fine:
704
705>>> def f():
706... try:
707... try:
708... yield 12
Tim Peters3caca232001-12-06 06:23:26 +0000709... 1//0
Tim Petersea2e97a2001-06-24 07:10:02 +0000710... except ZeroDivisionError:
711... yield 666
712... except:
713... try:
714... x = 12
715... finally:
716... yield 12
717... except:
718... return
719>>> list(f())
720[12, 666]
Tim Petersb6c3cea2001-06-26 03:36:28 +0000721
722>>> def f():
Tim Peters08a898f2001-06-28 01:52:22 +0000723... yield
724Traceback (most recent call last):
725SyntaxError: invalid syntax
726
727>>> def f():
728... if 0:
729... yield
730Traceback (most recent call last):
731SyntaxError: invalid syntax
732
733>>> def f():
Tim Petersb6c3cea2001-06-26 03:36:28 +0000734... if 0:
735... yield 1
736>>> type(f())
737<type 'generator'>
738
739>>> def f():
740... if "":
741... yield None
742>>> type(f())
743<type 'generator'>
744
745>>> def f():
746... return
747... try:
748... if x==4:
749... pass
750... elif 0:
751... try:
Tim Peters3caca232001-12-06 06:23:26 +0000752... 1//0
Tim Petersb6c3cea2001-06-26 03:36:28 +0000753... except SyntaxError:
754... pass
755... else:
756... if 0:
757... while 12:
758... x += 1
759... yield 2 # don't blink
760... f(a, b, c, d, e)
761... else:
762... pass
763... except:
764... x = 1
765... return
766>>> type(f())
767<type 'generator'>
768
769>>> def f():
770... if 0:
771... def g():
772... yield 1
773...
774>>> type(f())
Guido van Rossum297abad2001-08-16 08:32:39 +0000775<type 'NoneType'>
Tim Petersb6c3cea2001-06-26 03:36:28 +0000776
777>>> def f():
778... if 0:
779... class C:
780... def __init__(self):
781... yield 1
782... def f(self):
783... yield 2
784>>> type(f())
Guido van Rossum297abad2001-08-16 08:32:39 +0000785<type 'NoneType'>
Tim Peters08a898f2001-06-28 01:52:22 +0000786
787>>> def f():
788... if 0:
789... return
790... if 0:
791... yield 2
792>>> type(f())
793<type 'generator'>
794
795
796>>> def f():
797... if 0:
798... lambda x: x # shouldn't trigger here
799... return # or here
800... def f(i):
801... return 2*i # or here
802... if 0:
803... return 3 # but *this* sucks (line 8)
804... if 0:
805... yield 2 # because it's a generator
806Traceback (most recent call last):
807SyntaxError: 'return' with argument inside generator (<string>, line 8)
Guido van Rossumc5fe5eb2002-06-12 03:45:21 +0000808
809This one caused a crash (see SF bug 567538):
810
811>>> def f():
812... for i in range(3):
813... try:
814... continue
815... finally:
816... yield i
817...
818>>> g = f()
819>>> print g.next()
8200
821>>> print g.next()
8221
823>>> print g.next()
8242
825>>> print g.next()
826Traceback (most recent call last):
827StopIteration
Tim Petersea2e97a2001-06-24 07:10:02 +0000828"""
829
Tim Petersbe4f0a72001-06-29 02:41:16 +0000830# conjoin is a simple backtracking generator, named in honor of Icon's
831# "conjunction" control structure. Pass a list of no-argument functions
832# that return iterable objects. Easiest to explain by example: assume the
833# function list [x, y, z] is passed. Then conjoin acts like:
834#
835# def g():
836# values = [None] * 3
837# for values[0] in x():
838# for values[1] in y():
839# for values[2] in z():
840# yield values
841#
842# So some 3-lists of values *may* be generated, each time we successfully
843# get into the innermost loop. If an iterator fails (is exhausted) before
844# then, it "backtracks" to get the next value from the nearest enclosing
845# iterator (the one "to the left"), and starts all over again at the next
846# slot (pumps a fresh iterator). Of course this is most useful when the
847# iterators have side-effects, so that which values *can* be generated at
848# each slot depend on the values iterated at previous slots.
849
850def conjoin(gs):
851
852 values = [None] * len(gs)
853
854 def gen(i, values=values):
855 if i >= len(gs):
856 yield values
857 else:
858 for values[i] in gs[i]():
859 for x in gen(i+1):
860 yield x
861
862 for x in gen(0):
863 yield x
864
Tim Petersc468fd22001-06-30 07:29:44 +0000865# That works fine, but recursing a level and checking i against len(gs) for
866# each item produced is inefficient. By doing manual loop unrolling across
867# generator boundaries, it's possible to eliminate most of that overhead.
868# This isn't worth the bother *in general* for generators, but conjoin() is
869# a core building block for some CPU-intensive generator applications.
870
871def conjoin(gs):
872
873 n = len(gs)
874 values = [None] * n
875
876 # Do one loop nest at time recursively, until the # of loop nests
877 # remaining is divisible by 3.
878
879 def gen(i, values=values):
880 if i >= n:
881 yield values
882
883 elif (n-i) % 3:
884 ip1 = i+1
885 for values[i] in gs[i]():
886 for x in gen(ip1):
887 yield x
888
889 else:
890 for x in _gen3(i):
891 yield x
892
893 # Do three loop nests at a time, recursing only if at least three more
894 # remain. Don't call directly: this is an internal optimization for
895 # gen's use.
896
897 def _gen3(i, values=values):
898 assert i < n and (n-i) % 3 == 0
899 ip1, ip2, ip3 = i+1, i+2, i+3
900 g, g1, g2 = gs[i : ip3]
901
902 if ip3 >= n:
903 # These are the last three, so we can yield values directly.
904 for values[i] in g():
905 for values[ip1] in g1():
906 for values[ip2] in g2():
907 yield values
908
909 else:
910 # At least 6 loop nests remain; peel off 3 and recurse for the
911 # rest.
912 for values[i] in g():
913 for values[ip1] in g1():
914 for values[ip2] in g2():
915 for x in _gen3(ip3):
916 yield x
917
918 for x in gen(0):
919 yield x
920
unknown31569562001-07-04 22:11:22 +0000921# And one more approach: For backtracking apps like the Knight's Tour
922# solver below, the number of backtracking levels can be enormous (one
923# level per square, for the Knight's Tour, so that e.g. a 100x100 board
924# needs 10,000 levels). In such cases Python is likely to run out of
925# stack space due to recursion. So here's a recursion-free version of
926# conjoin too.
927# NOTE WELL: This allows large problems to be solved with only trivial
928# demands on stack space. Without explicitly resumable generators, this is
Tim Peters9a8c8e22001-07-13 09:12:12 +0000929# much harder to achieve. OTOH, this is much slower (up to a factor of 2)
930# than the fancy unrolled recursive conjoin.
unknown31569562001-07-04 22:11:22 +0000931
932def flat_conjoin(gs): # rename to conjoin to run tests with this instead
933 n = len(gs)
934 values = [None] * n
935 iters = [None] * n
Tim Peters9a8c8e22001-07-13 09:12:12 +0000936 _StopIteration = StopIteration # make local because caught a *lot*
unknown31569562001-07-04 22:11:22 +0000937 i = 0
Tim Peters9a8c8e22001-07-13 09:12:12 +0000938 while 1:
939 # Descend.
940 try:
941 while i < n:
942 it = iters[i] = gs[i]().next
943 values[i] = it()
944 i += 1
945 except _StopIteration:
946 pass
unknown31569562001-07-04 22:11:22 +0000947 else:
Tim Peters9a8c8e22001-07-13 09:12:12 +0000948 assert i == n
949 yield values
unknown31569562001-07-04 22:11:22 +0000950
Tim Peters9a8c8e22001-07-13 09:12:12 +0000951 # Backtrack until an older iterator can be resumed.
952 i -= 1
unknown31569562001-07-04 22:11:22 +0000953 while i >= 0:
954 try:
955 values[i] = iters[i]()
Tim Peters9a8c8e22001-07-13 09:12:12 +0000956 # Success! Start fresh at next level.
unknown31569562001-07-04 22:11:22 +0000957 i += 1
958 break
Tim Peters9a8c8e22001-07-13 09:12:12 +0000959 except _StopIteration:
960 # Continue backtracking.
961 i -= 1
962 else:
963 assert i < 0
964 break
unknown31569562001-07-04 22:11:22 +0000965
Tim Petersbe4f0a72001-06-29 02:41:16 +0000966# A conjoin-based N-Queens solver.
967
968class Queens:
969 def __init__(self, n):
970 self.n = n
971 rangen = range(n)
972
973 # Assign a unique int to each column and diagonal.
974 # columns: n of those, range(n).
975 # NW-SE diagonals: 2n-1 of these, i-j unique and invariant along
976 # each, smallest i-j is 0-(n-1) = 1-n, so add n-1 to shift to 0-
977 # based.
978 # NE-SW diagonals: 2n-1 of these, i+j unique and invariant along
979 # each, smallest i+j is 0, largest is 2n-2.
980
981 # For each square, compute a bit vector of the columns and
982 # diagonals it covers, and for each row compute a function that
983 # generates the possiblities for the columns in that row.
984 self.rowgenerators = []
985 for i in rangen:
986 rowuses = [(1L << j) | # column ordinal
987 (1L << (n + i-j + n-1)) | # NW-SE ordinal
988 (1L << (n + 2*n-1 + i+j)) # NE-SW ordinal
989 for j in rangen]
990
991 def rowgen(rowuses=rowuses):
992 for j in rangen:
993 uses = rowuses[j]
Tim Petersc468fd22001-06-30 07:29:44 +0000994 if uses & self.used == 0:
995 self.used |= uses
996 yield j
997 self.used &= ~uses
Tim Petersbe4f0a72001-06-29 02:41:16 +0000998
999 self.rowgenerators.append(rowgen)
1000
1001 # Generate solutions.
1002 def solve(self):
1003 self.used = 0
1004 for row2col in conjoin(self.rowgenerators):
1005 yield row2col
1006
1007 def printsolution(self, row2col):
1008 n = self.n
1009 assert n == len(row2col)
1010 sep = "+" + "-+" * n
1011 print sep
1012 for i in range(n):
1013 squares = [" " for j in range(n)]
1014 squares[row2col[i]] = "Q"
1015 print "|" + "|".join(squares) + "|"
1016 print sep
1017
unknown31569562001-07-04 22:11:22 +00001018# A conjoin-based Knight's Tour solver. This is pretty sophisticated
1019# (e.g., when used with flat_conjoin above, and passing hard=1 to the
1020# constructor, a 200x200 Knight's Tour was found quickly -- note that we're
Tim Peters9a8c8e22001-07-13 09:12:12 +00001021# creating 10s of thousands of generators then!), and is lengthy.
unknown31569562001-07-04 22:11:22 +00001022
1023class Knights:
Tim Peters9a8c8e22001-07-13 09:12:12 +00001024 def __init__(self, m, n, hard=0):
1025 self.m, self.n = m, n
unknown31569562001-07-04 22:11:22 +00001026
Tim Peters9a8c8e22001-07-13 09:12:12 +00001027 # solve() will set up succs[i] to be a list of square #i's
1028 # successors.
1029 succs = self.succs = []
unknown31569562001-07-04 22:11:22 +00001030
Tim Peters9a8c8e22001-07-13 09:12:12 +00001031 # Remove i0 from each of its successor's successor lists, i.e.
1032 # successors can't go back to i0 again. Return 0 if we can
1033 # detect this makes a solution impossible, else return 1.
unknown31569562001-07-04 22:11:22 +00001034
Tim Peters9a8c8e22001-07-13 09:12:12 +00001035 def remove_from_successors(i0, len=len):
unknown31569562001-07-04 22:11:22 +00001036 # If we remove all exits from a free square, we're dead:
1037 # even if we move to it next, we can't leave it again.
1038 # If we create a square with one exit, we must visit it next;
1039 # else somebody else will have to visit it, and since there's
1040 # only one adjacent, there won't be a way to leave it again.
1041 # Finelly, if we create more than one free square with a
1042 # single exit, we can only move to one of them next, leaving
1043 # the other one a dead end.
1044 ne0 = ne1 = 0
1045 for i in succs[i0]:
Tim Peters9a8c8e22001-07-13 09:12:12 +00001046 s = succs[i]
1047 s.remove(i0)
1048 e = len(s)
1049 if e == 0:
1050 ne0 += 1
1051 elif e == 1:
1052 ne1 += 1
unknown31569562001-07-04 22:11:22 +00001053 return ne0 == 0 and ne1 < 2
1054
Tim Peters9a8c8e22001-07-13 09:12:12 +00001055 # Put i0 back in each of its successor's successor lists.
1056
1057 def add_to_successors(i0):
unknown31569562001-07-04 22:11:22 +00001058 for i in succs[i0]:
Tim Peters9a8c8e22001-07-13 09:12:12 +00001059 succs[i].append(i0)
unknown31569562001-07-04 22:11:22 +00001060
1061 # Generate the first move.
1062 def first():
Tim Peters9a8c8e22001-07-13 09:12:12 +00001063 if m < 1 or n < 1:
unknown31569562001-07-04 22:11:22 +00001064 return
1065
unknown31569562001-07-04 22:11:22 +00001066 # Since we're looking for a cycle, it doesn't matter where we
1067 # start. Starting in a corner makes the 2nd move easy.
Tim Peters9a8c8e22001-07-13 09:12:12 +00001068 corner = self.coords2index(0, 0)
1069 remove_from_successors(corner)
unknown31569562001-07-04 22:11:22 +00001070 self.lastij = corner
1071 yield corner
Tim Peters9a8c8e22001-07-13 09:12:12 +00001072 add_to_successors(corner)
unknown31569562001-07-04 22:11:22 +00001073
1074 # Generate the second moves.
1075 def second():
Tim Peters9a8c8e22001-07-13 09:12:12 +00001076 corner = self.coords2index(0, 0)
unknown31569562001-07-04 22:11:22 +00001077 assert self.lastij == corner # i.e., we started in the corner
Tim Peters9a8c8e22001-07-13 09:12:12 +00001078 if m < 3 or n < 3:
unknown31569562001-07-04 22:11:22 +00001079 return
Tim Peters9a8c8e22001-07-13 09:12:12 +00001080 assert len(succs[corner]) == 2
1081 assert self.coords2index(1, 2) in succs[corner]
1082 assert self.coords2index(2, 1) in succs[corner]
unknown31569562001-07-04 22:11:22 +00001083 # Only two choices. Whichever we pick, the other must be the
Tim Peters9a8c8e22001-07-13 09:12:12 +00001084 # square picked on move m*n, as it's the only way to get back
unknown31569562001-07-04 22:11:22 +00001085 # to (0, 0). Save its index in self.final so that moves before
1086 # the last know it must be kept free.
1087 for i, j in (1, 2), (2, 1):
Tim Peters9a8c8e22001-07-13 09:12:12 +00001088 this = self.coords2index(i, j)
1089 final = self.coords2index(3-i, 3-j)
unknown31569562001-07-04 22:11:22 +00001090 self.final = final
unknown31569562001-07-04 22:11:22 +00001091
Tim Peters9a8c8e22001-07-13 09:12:12 +00001092 remove_from_successors(this)
1093 succs[final].append(corner)
unknown31569562001-07-04 22:11:22 +00001094 self.lastij = this
1095 yield this
Tim Peters9a8c8e22001-07-13 09:12:12 +00001096 succs[final].remove(corner)
1097 add_to_successors(this)
unknown31569562001-07-04 22:11:22 +00001098
Tim Peters9a8c8e22001-07-13 09:12:12 +00001099 # Generate moves 3 thru m*n-1.
1100 def advance(len=len):
unknown31569562001-07-04 22:11:22 +00001101 # If some successor has only one exit, must take it.
1102 # Else favor successors with fewer exits.
1103 candidates = []
1104 for i in succs[self.lastij]:
Tim Peters9a8c8e22001-07-13 09:12:12 +00001105 e = len(succs[i])
1106 assert e > 0, "else remove_from_successors() pruning flawed"
1107 if e == 1:
1108 candidates = [(e, i)]
1109 break
1110 candidates.append((e, i))
unknown31569562001-07-04 22:11:22 +00001111 else:
1112 candidates.sort()
1113
1114 for e, i in candidates:
1115 if i != self.final:
Tim Peters9a8c8e22001-07-13 09:12:12 +00001116 if remove_from_successors(i):
unknown31569562001-07-04 22:11:22 +00001117 self.lastij = i
1118 yield i
Tim Peters9a8c8e22001-07-13 09:12:12 +00001119 add_to_successors(i)
unknown31569562001-07-04 22:11:22 +00001120
Tim Peters9a8c8e22001-07-13 09:12:12 +00001121 # Generate moves 3 thru m*n-1. Alternative version using a
unknown31569562001-07-04 22:11:22 +00001122 # stronger (but more expensive) heuristic to order successors.
Tim Peters9a8c8e22001-07-13 09:12:12 +00001123 # Since the # of backtracking levels is m*n, a poor move early on
1124 # can take eons to undo. Smallest square board for which this
1125 # matters a lot is 52x52.
1126 def advance_hard(vmid=(m-1)/2.0, hmid=(n-1)/2.0, len=len):
unknown31569562001-07-04 22:11:22 +00001127 # If some successor has only one exit, must take it.
1128 # Else favor successors with fewer exits.
1129 # Break ties via max distance from board centerpoint (favor
1130 # corners and edges whenever possible).
1131 candidates = []
1132 for i in succs[self.lastij]:
Tim Peters9a8c8e22001-07-13 09:12:12 +00001133 e = len(succs[i])
1134 assert e > 0, "else remove_from_successors() pruning flawed"
1135 if e == 1:
1136 candidates = [(e, 0, i)]
1137 break
1138 i1, j1 = self.index2coords(i)
1139 d = (i1 - vmid)**2 + (j1 - hmid)**2
1140 candidates.append((e, -d, i))
unknown31569562001-07-04 22:11:22 +00001141 else:
1142 candidates.sort()
1143
1144 for e, d, i in candidates:
1145 if i != self.final:
Tim Peters9a8c8e22001-07-13 09:12:12 +00001146 if remove_from_successors(i):
unknown31569562001-07-04 22:11:22 +00001147 self.lastij = i
1148 yield i
Tim Peters9a8c8e22001-07-13 09:12:12 +00001149 add_to_successors(i)
unknown31569562001-07-04 22:11:22 +00001150
1151 # Generate the last move.
1152 def last():
1153 assert self.final in succs[self.lastij]
1154 yield self.final
1155
Tim Peters9a8c8e22001-07-13 09:12:12 +00001156 if m*n < 4:
1157 self.squaregenerators = [first]
unknown31569562001-07-04 22:11:22 +00001158 else:
Tim Peters9a8c8e22001-07-13 09:12:12 +00001159 self.squaregenerators = [first, second] + \
1160 [hard and advance_hard or advance] * (m*n - 3) + \
unknown31569562001-07-04 22:11:22 +00001161 [last]
1162
Tim Peters9a8c8e22001-07-13 09:12:12 +00001163 def coords2index(self, i, j):
1164 assert 0 <= i < self.m
1165 assert 0 <= j < self.n
1166 return i * self.n + j
1167
1168 def index2coords(self, index):
1169 assert 0 <= index < self.m * self.n
1170 return divmod(index, self.n)
1171
1172 def _init_board(self):
1173 succs = self.succs
1174 del succs[:]
1175 m, n = self.m, self.n
1176 c2i = self.coords2index
1177
1178 offsets = [( 1, 2), ( 2, 1), ( 2, -1), ( 1, -2),
1179 (-1, -2), (-2, -1), (-2, 1), (-1, 2)]
1180 rangen = range(n)
1181 for i in range(m):
1182 for j in rangen:
1183 s = [c2i(i+io, j+jo) for io, jo in offsets
1184 if 0 <= i+io < m and
1185 0 <= j+jo < n]
1186 succs.append(s)
1187
unknown31569562001-07-04 22:11:22 +00001188 # Generate solutions.
1189 def solve(self):
Tim Peters9a8c8e22001-07-13 09:12:12 +00001190 self._init_board()
1191 for x in conjoin(self.squaregenerators):
unknown31569562001-07-04 22:11:22 +00001192 yield x
1193
1194 def printsolution(self, x):
Tim Peters9a8c8e22001-07-13 09:12:12 +00001195 m, n = self.m, self.n
1196 assert len(x) == m*n
1197 w = len(str(m*n))
unknown31569562001-07-04 22:11:22 +00001198 format = "%" + str(w) + "d"
1199
Tim Peters9a8c8e22001-07-13 09:12:12 +00001200 squares = [[None] * n for i in range(m)]
unknown31569562001-07-04 22:11:22 +00001201 k = 1
1202 for i in x:
Tim Peters9a8c8e22001-07-13 09:12:12 +00001203 i1, j1 = self.index2coords(i)
unknown31569562001-07-04 22:11:22 +00001204 squares[i1][j1] = format % k
1205 k += 1
1206
1207 sep = "+" + ("-" * w + "+") * n
1208 print sep
Tim Peters9a8c8e22001-07-13 09:12:12 +00001209 for i in range(m):
unknown31569562001-07-04 22:11:22 +00001210 row = squares[i]
1211 print "|" + "|".join(row) + "|"
1212 print sep
1213
Tim Petersbe4f0a72001-06-29 02:41:16 +00001214conjoin_tests = """
1215
1216Generate the 3-bit binary numbers in order. This illustrates dumbest-
1217possible use of conjoin, just to generate the full cross-product.
1218
unknown31569562001-07-04 22:11:22 +00001219>>> for c in conjoin([lambda: iter((0, 1))] * 3):
Tim Petersbe4f0a72001-06-29 02:41:16 +00001220... print c
1221[0, 0, 0]
1222[0, 0, 1]
1223[0, 1, 0]
1224[0, 1, 1]
1225[1, 0, 0]
1226[1, 0, 1]
1227[1, 1, 0]
1228[1, 1, 1]
1229
Tim Petersc468fd22001-06-30 07:29:44 +00001230For efficiency in typical backtracking apps, conjoin() yields the same list
1231object each time. So if you want to save away a full account of its
1232generated sequence, you need to copy its results.
1233
1234>>> def gencopy(iterator):
1235... for x in iterator:
1236... yield x[:]
1237
1238>>> for n in range(10):
unknown31569562001-07-04 22:11:22 +00001239... all = list(gencopy(conjoin([lambda: iter((0, 1))] * n)))
Tim Petersc468fd22001-06-30 07:29:44 +00001240... print n, len(all), all[0] == [0] * n, all[-1] == [1] * n
Guido van Rossum77f6a652002-04-03 22:41:51 +000012410 1 True True
12421 2 True True
12432 4 True True
12443 8 True True
12454 16 True True
12465 32 True True
12476 64 True True
12487 128 True True
12498 256 True True
12509 512 True True
Tim Petersc468fd22001-06-30 07:29:44 +00001251
Tim Petersbe4f0a72001-06-29 02:41:16 +00001252And run an 8-queens solver.
1253
1254>>> q = Queens(8)
1255>>> LIMIT = 2
1256>>> count = 0
1257>>> for row2col in q.solve():
1258... count += 1
1259... if count <= LIMIT:
1260... print "Solution", count
1261... q.printsolution(row2col)
1262Solution 1
1263+-+-+-+-+-+-+-+-+
1264|Q| | | | | | | |
1265+-+-+-+-+-+-+-+-+
1266| | | | |Q| | | |
1267+-+-+-+-+-+-+-+-+
1268| | | | | | | |Q|
1269+-+-+-+-+-+-+-+-+
1270| | | | | |Q| | |
1271+-+-+-+-+-+-+-+-+
1272| | |Q| | | | | |
1273+-+-+-+-+-+-+-+-+
1274| | | | | | |Q| |
1275+-+-+-+-+-+-+-+-+
1276| |Q| | | | | | |
1277+-+-+-+-+-+-+-+-+
1278| | | |Q| | | | |
1279+-+-+-+-+-+-+-+-+
1280Solution 2
1281+-+-+-+-+-+-+-+-+
1282|Q| | | | | | | |
1283+-+-+-+-+-+-+-+-+
1284| | | | | |Q| | |
1285+-+-+-+-+-+-+-+-+
1286| | | | | | | |Q|
1287+-+-+-+-+-+-+-+-+
1288| | |Q| | | | | |
1289+-+-+-+-+-+-+-+-+
1290| | | | | | |Q| |
1291+-+-+-+-+-+-+-+-+
1292| | | |Q| | | | |
1293+-+-+-+-+-+-+-+-+
1294| |Q| | | | | | |
1295+-+-+-+-+-+-+-+-+
1296| | | | |Q| | | |
1297+-+-+-+-+-+-+-+-+
1298
1299>>> print count, "solutions in all."
130092 solutions in all.
unknown31569562001-07-04 22:11:22 +00001301
1302And run a Knight's Tour on a 10x10 board. Note that there are about
130320,000 solutions even on a 6x6 board, so don't dare run this to exhaustion.
1304
Tim Peters9a8c8e22001-07-13 09:12:12 +00001305>>> k = Knights(10, 10)
unknown31569562001-07-04 22:11:22 +00001306>>> LIMIT = 2
1307>>> count = 0
1308>>> for x in k.solve():
1309... count += 1
1310... if count <= LIMIT:
1311... print "Solution", count
1312... k.printsolution(x)
1313... else:
1314... break
1315Solution 1
1316+---+---+---+---+---+---+---+---+---+---+
1317| 1| 58| 27| 34| 3| 40| 29| 10| 5| 8|
1318+---+---+---+---+---+---+---+---+---+---+
1319| 26| 35| 2| 57| 28| 33| 4| 7| 30| 11|
1320+---+---+---+---+---+---+---+---+---+---+
1321| 59|100| 73| 36| 41| 56| 39| 32| 9| 6|
1322+---+---+---+---+---+---+---+---+---+---+
1323| 74| 25| 60| 55| 72| 37| 42| 49| 12| 31|
1324+---+---+---+---+---+---+---+---+---+---+
1325| 61| 86| 99| 76| 63| 52| 47| 38| 43| 50|
1326+---+---+---+---+---+---+---+---+---+---+
1327| 24| 75| 62| 85| 54| 71| 64| 51| 48| 13|
1328+---+---+---+---+---+---+---+---+---+---+
1329| 87| 98| 91| 80| 77| 84| 53| 46| 65| 44|
1330+---+---+---+---+---+---+---+---+---+---+
1331| 90| 23| 88| 95| 70| 79| 68| 83| 14| 17|
1332+---+---+---+---+---+---+---+---+---+---+
1333| 97| 92| 21| 78| 81| 94| 19| 16| 45| 66|
1334+---+---+---+---+---+---+---+---+---+---+
1335| 22| 89| 96| 93| 20| 69| 82| 67| 18| 15|
1336+---+---+---+---+---+---+---+---+---+---+
1337Solution 2
1338+---+---+---+---+---+---+---+---+---+---+
1339| 1| 58| 27| 34| 3| 40| 29| 10| 5| 8|
1340+---+---+---+---+---+---+---+---+---+---+
1341| 26| 35| 2| 57| 28| 33| 4| 7| 30| 11|
1342+---+---+---+---+---+---+---+---+---+---+
1343| 59|100| 73| 36| 41| 56| 39| 32| 9| 6|
1344+---+---+---+---+---+---+---+---+---+---+
1345| 74| 25| 60| 55| 72| 37| 42| 49| 12| 31|
1346+---+---+---+---+---+---+---+---+---+---+
1347| 61| 86| 99| 76| 63| 52| 47| 38| 43| 50|
1348+---+---+---+---+---+---+---+---+---+---+
1349| 24| 75| 62| 85| 54| 71| 64| 51| 48| 13|
1350+---+---+---+---+---+---+---+---+---+---+
1351| 87| 98| 89| 80| 77| 84| 53| 46| 65| 44|
1352+---+---+---+---+---+---+---+---+---+---+
1353| 90| 23| 92| 95| 70| 79| 68| 83| 14| 17|
1354+---+---+---+---+---+---+---+---+---+---+
1355| 97| 88| 21| 78| 81| 94| 19| 16| 45| 66|
1356+---+---+---+---+---+---+---+---+---+---+
1357| 22| 91| 96| 93| 20| 69| 82| 67| 18| 15|
1358+---+---+---+---+---+---+---+---+---+---+
Tim Petersbe4f0a72001-06-29 02:41:16 +00001359"""
1360
Tim Petersf6ed0742001-06-27 07:17:57 +00001361__test__ = {"tut": tutorial_tests,
1362 "pep": pep_tests,
1363 "email": email_tests,
1364 "fun": fun_tests,
Tim Petersbe4f0a72001-06-29 02:41:16 +00001365 "syntax": syntax_tests,
1366 "conjoin": conjoin_tests}
Tim Peters1def3512001-06-23 20:27:04 +00001367
1368# Magic test name that regrtest.py invokes *after* importing this module.
1369# This worms around a bootstrap problem.
1370# Note that doctest and regrtest both look in sys.argv for a "-v" argument,
1371# so this works as expected in both ways of running regrtest.
Tim Petersa0a62222001-09-09 06:12:01 +00001372def test_main(verbose=None):
1373 import doctest, test_support, test_generators
Tim Petersa1d54552001-07-12 22:55:42 +00001374 if 0: # change to 1 to run forever (to check for leaks)
1375 while 1:
Tim Peters2106ef02001-06-25 01:30:12 +00001376 doctest.master = None
Tim Petersa0a62222001-09-09 06:12:01 +00001377 test_support.run_doctest(test_generators, verbose)
Tim Petersa1d54552001-07-12 22:55:42 +00001378 print ".",
Tim Peters2106ef02001-06-25 01:30:12 +00001379 else:
Tim Petersa0a62222001-09-09 06:12:01 +00001380 test_support.run_doctest(test_generators, verbose)
Tim Peters1def3512001-06-23 20:27:04 +00001381
1382# This part isn't needed for regrtest, but for running the test directly.
1383if __name__ == "__main__":
Tim Petersa0a62222001-09-09 06:12:01 +00001384 test_main(1)