blob: 2476a275f9d94650ef2d2efa2fad0e241c1fb97b [file] [log] [blame]
Tim Peters5ba58662001-07-16 02:29:45 +00001from __future__ import generators
2
Tim Peters6ba5f792001-06-23 20:45:43 +00003tutorial_tests = """
Tim Peters1def3512001-06-23 20:27:04 +00004Let's try a simple generator:
5
6 >>> def f():
7 ... yield 1
8 ... yield 2
9
Tim Petersb9e9ff12001-06-24 03:44:52 +000010 >>> for i in f():
11 ... print i
12 1
13 2
Tim Peters1def3512001-06-23 20:27:04 +000014 >>> g = f()
15 >>> g.next()
16 1
17 >>> g.next()
18 2
Tim Petersea2e97a2001-06-24 07:10:02 +000019
Tim Peters2106ef02001-06-25 01:30:12 +000020"Falling off the end" stops the generator:
Tim Petersea2e97a2001-06-24 07:10:02 +000021
Tim Peters1def3512001-06-23 20:27:04 +000022 >>> g.next()
23 Traceback (most recent call last):
24 File "<stdin>", line 1, in ?
25 File "<stdin>", line 2, in g
26 StopIteration
27
Tim Petersea2e97a2001-06-24 07:10:02 +000028"return" also stops the generator:
Tim Peters1def3512001-06-23 20:27:04 +000029
30 >>> def f():
31 ... yield 1
32 ... return
33 ... yield 2 # never reached
34 ...
35 >>> g = f()
36 >>> g.next()
37 1
38 >>> g.next()
39 Traceback (most recent call last):
40 File "<stdin>", line 1, in ?
41 File "<stdin>", line 3, in f
42 StopIteration
43 >>> g.next() # once stopped, can't be resumed
44 Traceback (most recent call last):
45 File "<stdin>", line 1, in ?
46 StopIteration
47
48"raise StopIteration" stops the generator too:
49
50 >>> def f():
51 ... yield 1
Tim Peters34463652001-07-12 22:43:41 +000052 ... raise StopIteration
Tim Peters1def3512001-06-23 20:27:04 +000053 ... yield 2 # never reached
54 ...
55 >>> g = f()
56 >>> g.next()
57 1
58 >>> g.next()
59 Traceback (most recent call last):
60 File "<stdin>", line 1, in ?
61 StopIteration
62 >>> g.next()
63 Traceback (most recent call last):
64 File "<stdin>", line 1, in ?
65 StopIteration
66
67However, they are not exactly equivalent:
68
69 >>> def g1():
70 ... try:
71 ... return
72 ... except:
73 ... yield 1
74 ...
75 >>> list(g1())
76 []
77
78 >>> def g2():
79 ... try:
80 ... raise StopIteration
81 ... except:
82 ... yield 42
83 >>> print list(g2())
84 [42]
85
86This may be surprising at first:
87
88 >>> def g3():
89 ... try:
90 ... return
91 ... finally:
92 ... yield 1
93 ...
94 >>> list(g3())
95 [1]
96
97Let's create an alternate range() function implemented as a generator:
98
99 >>> def yrange(n):
100 ... for i in range(n):
101 ... yield i
102 ...
103 >>> list(yrange(5))
104 [0, 1, 2, 3, 4]
105
106Generators always return to the most recent caller:
107
108 >>> def creator():
109 ... r = yrange(5)
110 ... print "creator", r.next()
111 ... return r
112 ...
113 >>> def caller():
114 ... r = creator()
115 ... for i in r:
116 ... print "caller", i
117 ...
118 >>> caller()
119 creator 0
120 caller 1
121 caller 2
122 caller 3
123 caller 4
124
125Generators can call other generators:
126
127 >>> def zrange(n):
128 ... for i in yrange(n):
129 ... yield i
130 ...
131 >>> list(zrange(5))
132 [0, 1, 2, 3, 4]
133
134"""
135
Tim Peters6ba5f792001-06-23 20:45:43 +0000136# The examples from PEP 255.
137
138pep_tests = """
139
140Specification: Return
141
142 Note that return isn't always equivalent to raising StopIteration: the
143 difference lies in how enclosing try/except constructs are treated.
144 For example,
145
146 >>> def f1():
147 ... try:
148 ... return
149 ... except:
150 ... yield 1
151 >>> print list(f1())
152 []
153
154 because, as in any function, return simply exits, but
155
156 >>> def f2():
157 ... try:
158 ... raise StopIteration
159 ... except:
160 ... yield 42
161 >>> print list(f2())
162 [42]
163
164 because StopIteration is captured by a bare "except", as is any
165 exception.
166
167Specification: Generators and Exception Propagation
168
169 >>> def f():
170 ... return 1/0
171 >>> def g():
172 ... yield f() # the zero division exception propagates
173 ... yield 42 # and we'll never get here
174 >>> k = g()
175 >>> k.next()
176 Traceback (most recent call last):
177 File "<stdin>", line 1, in ?
178 File "<stdin>", line 2, in g
179 File "<stdin>", line 2, in f
180 ZeroDivisionError: integer division or modulo by zero
181 >>> k.next() # and the generator cannot be resumed
182 Traceback (most recent call last):
183 File "<stdin>", line 1, in ?
184 StopIteration
185 >>>
186
187Specification: Try/Except/Finally
188
189 >>> def f():
190 ... try:
191 ... yield 1
192 ... try:
193 ... yield 2
194 ... 1/0
195 ... yield 3 # never get here
196 ... except ZeroDivisionError:
197 ... yield 4
198 ... yield 5
199 ... raise
200 ... except:
201 ... yield 6
202 ... yield 7 # the "raise" above stops this
203 ... except:
204 ... yield 8
205 ... yield 9
206 ... try:
207 ... x = 12
208 ... finally:
209 ... yield 10
210 ... yield 11
211 >>> print list(f())
212 [1, 2, 4, 5, 8, 9, 10, 11]
213 >>>
214
Tim Peters6ba5f792001-06-23 20:45:43 +0000215Guido's binary tree example.
216
217 >>> # A binary tree class.
218 >>> class Tree:
219 ...
220 ... def __init__(self, label, left=None, right=None):
221 ... self.label = label
222 ... self.left = left
223 ... self.right = right
224 ...
225 ... def __repr__(self, level=0, indent=" "):
226 ... s = level*indent + `self.label`
227 ... if self.left:
228 ... s = s + "\\n" + self.left.__repr__(level+1, indent)
229 ... if self.right:
230 ... s = s + "\\n" + self.right.__repr__(level+1, indent)
231 ... return s
232 ...
233 ... def __iter__(self):
234 ... return inorder(self)
235
236 >>> # Create a Tree from a list.
237 >>> def tree(list):
238 ... n = len(list)
239 ... if n == 0:
240 ... return []
241 ... i = n / 2
242 ... return Tree(list[i], tree(list[:i]), tree(list[i+1:]))
243
244 >>> # Show it off: create a tree.
245 >>> t = tree("ABCDEFGHIJKLMNOPQRSTUVWXYZ")
246
247 >>> # A recursive generator that generates Tree leaves in in-order.
248 >>> def inorder(t):
249 ... if t:
250 ... for x in inorder(t.left):
251 ... yield x
252 ... yield t.label
253 ... for x in inorder(t.right):
254 ... yield x
255
256 >>> # Show it off: create a tree.
257 ... t = tree("ABCDEFGHIJKLMNOPQRSTUVWXYZ")
258 ... # Print the nodes of the tree in in-order.
259 ... for x in t:
260 ... print x,
261 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
262
263 >>> # A non-recursive generator.
264 >>> def inorder(node):
265 ... stack = []
266 ... while node:
267 ... while node.left:
268 ... stack.append(node)
269 ... node = node.left
270 ... yield node.label
271 ... while not node.right:
272 ... try:
273 ... node = stack.pop()
274 ... except IndexError:
275 ... return
276 ... yield node.label
277 ... node = node.right
278
279 >>> # Exercise the non-recursive generator.
280 >>> for x in t:
281 ... print x,
282 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
283
284"""
285
Tim Petersb2bc6a92001-06-24 10:14:27 +0000286# Examples from Iterator-List and Python-Dev and c.l.py.
Tim Peters6ba5f792001-06-23 20:45:43 +0000287
288email_tests = """
289
290The difference between yielding None and returning it.
291
292>>> def g():
293... for i in range(3):
294... yield None
295... yield None
296... return
297>>> list(g())
298[None, None, None, None]
299
300Ensure that explicitly raising StopIteration acts like any other exception
301in try/except, not like a return.
302
303>>> def g():
304... yield 1
305... try:
306... raise StopIteration
307... except:
308... yield 2
309... yield 3
310>>> list(g())
311[1, 2, 3]
Tim Petersb9e9ff12001-06-24 03:44:52 +0000312
313A generator can't be resumed while it's already running.
314
315>>> def g():
316... i = me.next()
317... yield i
318>>> me = g()
319>>> me.next()
320Traceback (most recent call last):
321 ...
322 File "<string>", line 2, in g
323ValueError: generator already executing
Tim Petersb2bc6a92001-06-24 10:14:27 +0000324
325Next one was posted to c.l.py.
326
327>>> def gcomb(x, k):
328... "Generate all combinations of k elements from list x."
329...
330... if k > len(x):
331... return
332... if k == 0:
333... yield []
334... else:
335... first, rest = x[0], x[1:]
336... # A combination does or doesn't contain first.
337... # If it does, the remainder is a k-1 comb of rest.
338... for c in gcomb(rest, k-1):
339... c.insert(0, first)
340... yield c
341... # If it doesn't contain first, it's a k comb of rest.
342... for c in gcomb(rest, k):
343... yield c
344
345>>> seq = range(1, 5)
346>>> for k in range(len(seq) + 2):
347... print "%d-combs of %s:" % (k, seq)
348... for c in gcomb(seq, k):
349... print " ", c
3500-combs of [1, 2, 3, 4]:
351 []
3521-combs of [1, 2, 3, 4]:
353 [1]
354 [2]
355 [3]
356 [4]
3572-combs of [1, 2, 3, 4]:
358 [1, 2]
359 [1, 3]
360 [1, 4]
361 [2, 3]
362 [2, 4]
363 [3, 4]
3643-combs of [1, 2, 3, 4]:
365 [1, 2, 3]
366 [1, 2, 4]
367 [1, 3, 4]
368 [2, 3, 4]
3694-combs of [1, 2, 3, 4]:
370 [1, 2, 3, 4]
3715-combs of [1, 2, 3, 4]:
Tim Peters3e7b1a02001-06-25 19:46:25 +0000372
Tim Peterse77f2e22001-06-26 22:24:51 +0000373From the Iterators list, about the types of these things.
Tim Peters3e7b1a02001-06-25 19:46:25 +0000374
375>>> def g():
376... yield 1
377...
378>>> type(g)
379<type 'function'>
380>>> i = g()
381>>> type(i)
382<type 'generator'>
Tim Peters6d6c1a32001-08-02 04:15:00 +0000383
384XXX dir(object) *generally* doesn't return useful stuff in descr-branch.
Tim Peters3e7b1a02001-06-25 19:46:25 +0000385>>> dir(i)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000386[]
387
388Was hoping to see this instead:
Tim Peterse77f2e22001-06-26 22:24:51 +0000389['gi_frame', 'gi_running', 'next']
Tim Peters6d6c1a32001-08-02 04:15:00 +0000390
Tim Peters3e7b1a02001-06-25 19:46:25 +0000391>>> print i.next.__doc__
Tim Peters6d6c1a32001-08-02 04:15:00 +0000392x.next() -> the next value, or raise StopIteration
Tim Peters3e7b1a02001-06-25 19:46:25 +0000393>>> iter(i) is i
3941
395>>> import types
396>>> isinstance(i, types.GeneratorType)
3971
Tim Peterse77f2e22001-06-26 22:24:51 +0000398
399And more, added later.
400
401>>> i.gi_running
4020
403>>> type(i.gi_frame)
404<type 'frame'>
405>>> i.gi_running = 42
406Traceback (most recent call last):
407 ...
Guido van Rossum61cf7802001-08-10 21:25:24 +0000408TypeError: readonly attribute
Tim Peterse77f2e22001-06-26 22:24:51 +0000409>>> def g():
410... yield me.gi_running
411>>> me = g()
412>>> me.gi_running
4130
414>>> me.next()
4151
416>>> me.gi_running
4170
Tim Peters35302662001-07-02 01:38:33 +0000418
419A clever union-find implementation from c.l.py, due to David Eppstein.
420Sent: Friday, June 29, 2001 12:16 PM
421To: python-list@python.org
422Subject: Re: PEP 255: Simple Generators
423
424>>> class disjointSet:
425... def __init__(self, name):
426... self.name = name
427... self.parent = None
428... self.generator = self.generate()
429...
430... def generate(self):
431... while not self.parent:
432... yield self
433... for x in self.parent.generator:
434... yield x
435...
436... def find(self):
437... return self.generator.next()
438...
439... def union(self, parent):
440... if self.parent:
441... raise ValueError("Sorry, I'm not a root!")
442... self.parent = parent
443...
444... def __str__(self):
445... return self.name
Tim Peters35302662001-07-02 01:38:33 +0000446
447>>> names = "ABCDEFGHIJKLM"
448>>> sets = [disjointSet(name) for name in names]
449>>> roots = sets[:]
450
451>>> import random
452>>> random.seed(42)
453>>> while 1:
454... for s in sets:
455... print "%s->%s" % (s, s.find()),
456... print
457... if len(roots) > 1:
458... s1 = random.choice(roots)
459... roots.remove(s1)
460... s2 = random.choice(roots)
461... s1.union(s2)
462... print "merged", s1, "into", s2
463... else:
464... break
465A->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
466merged D into G
467A->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
468merged C into F
469A->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
470merged L into A
471A->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
472merged H into E
473A->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
474merged B into E
475A->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
476merged J into G
477A->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
478merged E into G
479A->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
480merged M into G
481A->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
482merged I into K
483A->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
484merged K into A
485A->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
486merged F into A
487A->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
488merged A into G
489A->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 +0000490"""
491
Tim Peters0f9da0a2001-06-23 21:01:47 +0000492# Fun tests (for sufficiently warped notions of "fun").
493
494fun_tests = """
495
496Build up to a recursive Sieve of Eratosthenes generator.
497
498>>> def firstn(g, n):
499... return [g.next() for i in range(n)]
500
501>>> def intsfrom(i):
502... while 1:
503... yield i
504... i += 1
505
506>>> firstn(intsfrom(5), 7)
507[5, 6, 7, 8, 9, 10, 11]
508
509>>> def exclude_multiples(n, ints):
510... for i in ints:
511... if i % n:
512... yield i
513
514>>> firstn(exclude_multiples(3, intsfrom(1)), 6)
515[1, 2, 4, 5, 7, 8]
516
517>>> def sieve(ints):
518... prime = ints.next()
519... yield prime
520... not_divisible_by_prime = exclude_multiples(prime, ints)
521... for p in sieve(not_divisible_by_prime):
522... yield p
523
524>>> primes = sieve(intsfrom(2))
525>>> firstn(primes, 20)
526[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 +0000527
Tim Petersf6ed0742001-06-27 07:17:57 +0000528
Tim Petersb9e9ff12001-06-24 03:44:52 +0000529Another famous problem: generate all integers of the form
530 2**i * 3**j * 5**k
531in increasing order, where i,j,k >= 0. Trickier than it may look at first!
532Try writing it without generators, and correctly, and without generating
5333 internal results for each result output.
534
535>>> def times(n, g):
536... for i in g:
537... yield n * i
538>>> firstn(times(10, intsfrom(1)), 10)
539[10, 20, 30, 40, 50, 60, 70, 80, 90, 100]
540
541>>> def merge(g, h):
542... ng = g.next()
543... nh = h.next()
544... while 1:
545... if ng < nh:
546... yield ng
547... ng = g.next()
548... elif ng > nh:
549... yield nh
550... nh = h.next()
551... else:
552... yield ng
553... ng = g.next()
554... nh = h.next()
555
Tim Petersf6ed0742001-06-27 07:17:57 +0000556The following works, but is doing a whale of a lot of redundant work --
557it's not clear how to get the internal uses of m235 to share a single
558generator. Note that me_times2 (etc) each need to see every element in the
559result sequence. So this is an example where lazy lists are more natural
560(you can look at the head of a lazy list any number of times).
Tim Petersb9e9ff12001-06-24 03:44:52 +0000561
562>>> def m235():
563... yield 1
564... me_times2 = times(2, m235())
565... me_times3 = times(3, m235())
566... me_times5 = times(5, m235())
567... for i in merge(merge(me_times2,
568... me_times3),
569... me_times5):
570... yield i
571
Tim Petersf6ed0742001-06-27 07:17:57 +0000572Don't print "too many" of these -- the implementation above is extremely
573inefficient: each call of m235() leads to 3 recursive calls, and in
574turn each of those 3 more, and so on, and so on, until we've descended
575enough levels to satisfy the print stmts. Very odd: when I printed 5
576lines of results below, this managed to screw up Win98's malloc in "the
577usual" way, i.e. the heap grew over 4Mb so Win98 started fragmenting
578address space, and it *looked* like a very slow leak.
579
Tim Petersb9e9ff12001-06-24 03:44:52 +0000580>>> result = m235()
Tim Petersf6ed0742001-06-27 07:17:57 +0000581>>> for i in range(3):
Tim Petersb9e9ff12001-06-24 03:44:52 +0000582... print firstn(result, 15)
583[1, 2, 3, 4, 5, 6, 8, 9, 10, 12, 15, 16, 18, 20, 24]
584[25, 27, 30, 32, 36, 40, 45, 48, 50, 54, 60, 64, 72, 75, 80]
585[81, 90, 96, 100, 108, 120, 125, 128, 135, 144, 150, 160, 162, 180, 192]
Tim Petersee309272001-06-24 05:47:06 +0000586
587Heh. Here's one way to get a shared list, complete with an excruciating
588namespace renaming trick. The *pretty* part is that the times() and merge()
589functions can be reused as-is, because they only assume their stream
590arguments are iterable -- a LazyList is the same as a generator to times().
591
592>>> class LazyList:
593... def __init__(self, g):
594... self.sofar = []
595... self.fetch = g.next
596...
597... def __getitem__(self, i):
598... sofar, fetch = self.sofar, self.fetch
599... while i >= len(sofar):
600... sofar.append(fetch())
601... return sofar[i]
602
603>>> def m235():
604... yield 1
Tim Petersea2e97a2001-06-24 07:10:02 +0000605... # Gack: m235 below actually refers to a LazyList.
Tim Petersee309272001-06-24 05:47:06 +0000606... me_times2 = times(2, m235)
607... me_times3 = times(3, m235)
608... me_times5 = times(5, m235)
609... for i in merge(merge(me_times2,
610... me_times3),
611... me_times5):
612... yield i
613
Tim Petersf6ed0742001-06-27 07:17:57 +0000614Print as many of these as you like -- *this* implementation is memory-
Neil Schemenauerb20e9db2001-07-12 13:26:41 +0000615efficient.
Tim Petersf6ed0742001-06-27 07:17:57 +0000616
Tim Petersee309272001-06-24 05:47:06 +0000617>>> m235 = LazyList(m235())
618>>> for i in range(5):
619... print [m235[j] for j in range(15*i, 15*(i+1))]
620[1, 2, 3, 4, 5, 6, 8, 9, 10, 12, 15, 16, 18, 20, 24]
621[25, 27, 30, 32, 36, 40, 45, 48, 50, 54, 60, 64, 72, 75, 80]
622[81, 90, 96, 100, 108, 120, 125, 128, 135, 144, 150, 160, 162, 180, 192]
623[200, 216, 225, 240, 243, 250, 256, 270, 288, 300, 320, 324, 360, 375, 384]
624[400, 405, 432, 450, 480, 486, 500, 512, 540, 576, 600, 625, 640, 648, 675]
Tim Petersf6ed0742001-06-27 07:17:57 +0000625
Tim Petersf6ed0742001-06-27 07:17:57 +0000626
627Ye olde Fibonacci generator, LazyList style.
628
629>>> def fibgen(a, b):
630...
631... def sum(g, h):
632... while 1:
633... yield g.next() + h.next()
634...
635... def tail(g):
636... g.next() # throw first away
637... for x in g:
638... yield x
639...
640... yield a
641... yield b
642... for s in sum(iter(fib),
643... tail(iter(fib))):
644... yield s
645
646>>> fib = LazyList(fibgen(1, 2))
647>>> firstn(iter(fib), 17)
648[1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597, 2584]
Tim Peters0f9da0a2001-06-23 21:01:47 +0000649"""
650
Tim Petersb6c3cea2001-06-26 03:36:28 +0000651# syntax_tests mostly provokes SyntaxErrors. Also fiddling with #if 0
652# hackery.
Tim Petersee309272001-06-24 05:47:06 +0000653
Tim Petersea2e97a2001-06-24 07:10:02 +0000654syntax_tests = """
655
656>>> def f():
657... return 22
658... yield 1
659Traceback (most recent call last):
660 ...
661SyntaxError: 'return' with argument inside generator (<string>, line 2)
662
663>>> def f():
664... yield 1
665... return 22
666Traceback (most recent call last):
667 ...
668SyntaxError: 'return' with argument inside generator (<string>, line 3)
669
670"return None" is not the same as "return" in a generator:
671
672>>> def f():
673... yield 1
674... return None
675Traceback (most recent call last):
676 ...
677SyntaxError: 'return' with argument inside generator (<string>, line 3)
678
679This one is fine:
680
681>>> def f():
682... yield 1
683... return
684
685>>> def f():
686... try:
687... yield 1
688... finally:
689... pass
690Traceback (most recent call last):
691 ...
692SyntaxError: 'yield' not allowed in a 'try' block with a 'finally' clause (<string>, line 3)
693
694>>> def f():
695... try:
696... try:
697... 1/0
698... except ZeroDivisionError:
699... yield 666 # bad because *outer* try has finally
700... except:
701... pass
702... finally:
703... pass
704Traceback (most recent call last):
705 ...
706SyntaxError: 'yield' not allowed in a 'try' block with a 'finally' clause (<string>, line 6)
707
708But this is fine:
709
710>>> def f():
711... try:
712... try:
713... yield 12
714... 1/0
715... except ZeroDivisionError:
716... yield 666
717... except:
718... try:
719... x = 12
720... finally:
721... yield 12
722... except:
723... return
724>>> list(f())
725[12, 666]
Tim Petersb6c3cea2001-06-26 03:36:28 +0000726
727>>> def f():
Tim Peters08a898f2001-06-28 01:52:22 +0000728... yield
729Traceback (most recent call last):
730SyntaxError: invalid syntax
731
732>>> def f():
733... if 0:
734... yield
735Traceback (most recent call last):
736SyntaxError: invalid syntax
737
738>>> def f():
Tim Petersb6c3cea2001-06-26 03:36:28 +0000739... if 0:
740... yield 1
741>>> type(f())
742<type 'generator'>
743
744>>> def f():
745... if "":
746... yield None
747>>> type(f())
748<type 'generator'>
749
750>>> def f():
751... return
752... try:
753... if x==4:
754... pass
755... elif 0:
756... try:
757... 1/0
758... except SyntaxError:
759... pass
760... else:
761... if 0:
762... while 12:
763... x += 1
764... yield 2 # don't blink
765... f(a, b, c, d, e)
766... else:
767... pass
768... except:
769... x = 1
770... return
771>>> type(f())
772<type 'generator'>
773
774>>> def f():
775... if 0:
776... def g():
777... yield 1
778...
779>>> type(f())
780<type 'None'>
781
782>>> def f():
783... if 0:
784... class C:
785... def __init__(self):
786... yield 1
787... def f(self):
788... yield 2
789>>> type(f())
790<type 'None'>
Tim Peters08a898f2001-06-28 01:52:22 +0000791
792>>> def f():
793... if 0:
794... return
795... if 0:
796... yield 2
797>>> type(f())
798<type 'generator'>
799
800
801>>> def f():
802... if 0:
803... lambda x: x # shouldn't trigger here
804... return # or here
805... def f(i):
806... return 2*i # or here
807... if 0:
808... return 3 # but *this* sucks (line 8)
809... if 0:
810... yield 2 # because it's a generator
811Traceback (most recent call last):
812SyntaxError: 'return' with argument inside generator (<string>, line 8)
Tim Petersea2e97a2001-06-24 07:10:02 +0000813"""
814
Tim Petersbe4f0a72001-06-29 02:41:16 +0000815# conjoin is a simple backtracking generator, named in honor of Icon's
816# "conjunction" control structure. Pass a list of no-argument functions
817# that return iterable objects. Easiest to explain by example: assume the
818# function list [x, y, z] is passed. Then conjoin acts like:
819#
820# def g():
821# values = [None] * 3
822# for values[0] in x():
823# for values[1] in y():
824# for values[2] in z():
825# yield values
826#
827# So some 3-lists of values *may* be generated, each time we successfully
828# get into the innermost loop. If an iterator fails (is exhausted) before
829# then, it "backtracks" to get the next value from the nearest enclosing
830# iterator (the one "to the left"), and starts all over again at the next
831# slot (pumps a fresh iterator). Of course this is most useful when the
832# iterators have side-effects, so that which values *can* be generated at
833# each slot depend on the values iterated at previous slots.
834
835def conjoin(gs):
836
837 values = [None] * len(gs)
838
839 def gen(i, values=values):
840 if i >= len(gs):
841 yield values
842 else:
843 for values[i] in gs[i]():
844 for x in gen(i+1):
845 yield x
846
847 for x in gen(0):
848 yield x
849
Tim Petersc468fd22001-06-30 07:29:44 +0000850# That works fine, but recursing a level and checking i against len(gs) for
851# each item produced is inefficient. By doing manual loop unrolling across
852# generator boundaries, it's possible to eliminate most of that overhead.
853# This isn't worth the bother *in general* for generators, but conjoin() is
854# a core building block for some CPU-intensive generator applications.
855
856def conjoin(gs):
857
858 n = len(gs)
859 values = [None] * n
860
861 # Do one loop nest at time recursively, until the # of loop nests
862 # remaining is divisible by 3.
863
864 def gen(i, values=values):
865 if i >= n:
866 yield values
867
868 elif (n-i) % 3:
869 ip1 = i+1
870 for values[i] in gs[i]():
871 for x in gen(ip1):
872 yield x
873
874 else:
875 for x in _gen3(i):
876 yield x
877
878 # Do three loop nests at a time, recursing only if at least three more
879 # remain. Don't call directly: this is an internal optimization for
880 # gen's use.
881
882 def _gen3(i, values=values):
883 assert i < n and (n-i) % 3 == 0
884 ip1, ip2, ip3 = i+1, i+2, i+3
885 g, g1, g2 = gs[i : ip3]
886
887 if ip3 >= n:
888 # These are the last three, so we can yield values directly.
889 for values[i] in g():
890 for values[ip1] in g1():
891 for values[ip2] in g2():
892 yield values
893
894 else:
895 # At least 6 loop nests remain; peel off 3 and recurse for the
896 # rest.
897 for values[i] in g():
898 for values[ip1] in g1():
899 for values[ip2] in g2():
900 for x in _gen3(ip3):
901 yield x
902
903 for x in gen(0):
904 yield x
905
unknown31569562001-07-04 22:11:22 +0000906# And one more approach: For backtracking apps like the Knight's Tour
907# solver below, the number of backtracking levels can be enormous (one
908# level per square, for the Knight's Tour, so that e.g. a 100x100 board
909# needs 10,000 levels). In such cases Python is likely to run out of
910# stack space due to recursion. So here's a recursion-free version of
911# conjoin too.
912# NOTE WELL: This allows large problems to be solved with only trivial
913# demands on stack space. Without explicitly resumable generators, this is
Tim Peters9a8c8e22001-07-13 09:12:12 +0000914# much harder to achieve. OTOH, this is much slower (up to a factor of 2)
915# than the fancy unrolled recursive conjoin.
unknown31569562001-07-04 22:11:22 +0000916
917def flat_conjoin(gs): # rename to conjoin to run tests with this instead
918 n = len(gs)
919 values = [None] * n
920 iters = [None] * n
Tim Peters9a8c8e22001-07-13 09:12:12 +0000921 _StopIteration = StopIteration # make local because caught a *lot*
unknown31569562001-07-04 22:11:22 +0000922 i = 0
Tim Peters9a8c8e22001-07-13 09:12:12 +0000923 while 1:
924 # Descend.
925 try:
926 while i < n:
927 it = iters[i] = gs[i]().next
928 values[i] = it()
929 i += 1
930 except _StopIteration:
931 pass
unknown31569562001-07-04 22:11:22 +0000932 else:
Tim Peters9a8c8e22001-07-13 09:12:12 +0000933 assert i == n
934 yield values
unknown31569562001-07-04 22:11:22 +0000935
Tim Peters9a8c8e22001-07-13 09:12:12 +0000936 # Backtrack until an older iterator can be resumed.
937 i -= 1
unknown31569562001-07-04 22:11:22 +0000938 while i >= 0:
939 try:
940 values[i] = iters[i]()
Tim Peters9a8c8e22001-07-13 09:12:12 +0000941 # Success! Start fresh at next level.
unknown31569562001-07-04 22:11:22 +0000942 i += 1
943 break
Tim Peters9a8c8e22001-07-13 09:12:12 +0000944 except _StopIteration:
945 # Continue backtracking.
946 i -= 1
947 else:
948 assert i < 0
949 break
unknown31569562001-07-04 22:11:22 +0000950
Tim Petersbe4f0a72001-06-29 02:41:16 +0000951# A conjoin-based N-Queens solver.
952
953class Queens:
954 def __init__(self, n):
955 self.n = n
956 rangen = range(n)
957
958 # Assign a unique int to each column and diagonal.
959 # columns: n of those, range(n).
960 # NW-SE diagonals: 2n-1 of these, i-j unique and invariant along
961 # each, smallest i-j is 0-(n-1) = 1-n, so add n-1 to shift to 0-
962 # based.
963 # NE-SW diagonals: 2n-1 of these, i+j unique and invariant along
964 # each, smallest i+j is 0, largest is 2n-2.
965
966 # For each square, compute a bit vector of the columns and
967 # diagonals it covers, and for each row compute a function that
968 # generates the possiblities for the columns in that row.
969 self.rowgenerators = []
970 for i in rangen:
971 rowuses = [(1L << j) | # column ordinal
972 (1L << (n + i-j + n-1)) | # NW-SE ordinal
973 (1L << (n + 2*n-1 + i+j)) # NE-SW ordinal
974 for j in rangen]
975
976 def rowgen(rowuses=rowuses):
977 for j in rangen:
978 uses = rowuses[j]
Tim Petersc468fd22001-06-30 07:29:44 +0000979 if uses & self.used == 0:
980 self.used |= uses
981 yield j
982 self.used &= ~uses
Tim Petersbe4f0a72001-06-29 02:41:16 +0000983
984 self.rowgenerators.append(rowgen)
985
986 # Generate solutions.
987 def solve(self):
988 self.used = 0
989 for row2col in conjoin(self.rowgenerators):
990 yield row2col
991
992 def printsolution(self, row2col):
993 n = self.n
994 assert n == len(row2col)
995 sep = "+" + "-+" * n
996 print sep
997 for i in range(n):
998 squares = [" " for j in range(n)]
999 squares[row2col[i]] = "Q"
1000 print "|" + "|".join(squares) + "|"
1001 print sep
1002
unknown31569562001-07-04 22:11:22 +00001003# A conjoin-based Knight's Tour solver. This is pretty sophisticated
1004# (e.g., when used with flat_conjoin above, and passing hard=1 to the
1005# constructor, a 200x200 Knight's Tour was found quickly -- note that we're
Tim Peters9a8c8e22001-07-13 09:12:12 +00001006# creating 10s of thousands of generators then!), and is lengthy.
unknown31569562001-07-04 22:11:22 +00001007
1008class Knights:
Tim Peters9a8c8e22001-07-13 09:12:12 +00001009 def __init__(self, m, n, hard=0):
1010 self.m, self.n = m, n
unknown31569562001-07-04 22:11:22 +00001011
Tim Peters9a8c8e22001-07-13 09:12:12 +00001012 # solve() will set up succs[i] to be a list of square #i's
1013 # successors.
1014 succs = self.succs = []
unknown31569562001-07-04 22:11:22 +00001015
Tim Peters9a8c8e22001-07-13 09:12:12 +00001016 # Remove i0 from each of its successor's successor lists, i.e.
1017 # successors can't go back to i0 again. Return 0 if we can
1018 # detect this makes a solution impossible, else return 1.
unknown31569562001-07-04 22:11:22 +00001019
Tim Peters9a8c8e22001-07-13 09:12:12 +00001020 def remove_from_successors(i0, len=len):
unknown31569562001-07-04 22:11:22 +00001021 # If we remove all exits from a free square, we're dead:
1022 # even if we move to it next, we can't leave it again.
1023 # If we create a square with one exit, we must visit it next;
1024 # else somebody else will have to visit it, and since there's
1025 # only one adjacent, there won't be a way to leave it again.
1026 # Finelly, if we create more than one free square with a
1027 # single exit, we can only move to one of them next, leaving
1028 # the other one a dead end.
1029 ne0 = ne1 = 0
1030 for i in succs[i0]:
Tim Peters9a8c8e22001-07-13 09:12:12 +00001031 s = succs[i]
1032 s.remove(i0)
1033 e = len(s)
1034 if e == 0:
1035 ne0 += 1
1036 elif e == 1:
1037 ne1 += 1
unknown31569562001-07-04 22:11:22 +00001038 return ne0 == 0 and ne1 < 2
1039
Tim Peters9a8c8e22001-07-13 09:12:12 +00001040 # Put i0 back in each of its successor's successor lists.
1041
1042 def add_to_successors(i0):
unknown31569562001-07-04 22:11:22 +00001043 for i in succs[i0]:
Tim Peters9a8c8e22001-07-13 09:12:12 +00001044 succs[i].append(i0)
unknown31569562001-07-04 22:11:22 +00001045
1046 # Generate the first move.
1047 def first():
Tim Peters9a8c8e22001-07-13 09:12:12 +00001048 if m < 1 or n < 1:
unknown31569562001-07-04 22:11:22 +00001049 return
1050
unknown31569562001-07-04 22:11:22 +00001051 # Since we're looking for a cycle, it doesn't matter where we
1052 # start. Starting in a corner makes the 2nd move easy.
Tim Peters9a8c8e22001-07-13 09:12:12 +00001053 corner = self.coords2index(0, 0)
1054 remove_from_successors(corner)
unknown31569562001-07-04 22:11:22 +00001055 self.lastij = corner
1056 yield corner
Tim Peters9a8c8e22001-07-13 09:12:12 +00001057 add_to_successors(corner)
unknown31569562001-07-04 22:11:22 +00001058
1059 # Generate the second moves.
1060 def second():
Tim Peters9a8c8e22001-07-13 09:12:12 +00001061 corner = self.coords2index(0, 0)
unknown31569562001-07-04 22:11:22 +00001062 assert self.lastij == corner # i.e., we started in the corner
Tim Peters9a8c8e22001-07-13 09:12:12 +00001063 if m < 3 or n < 3:
unknown31569562001-07-04 22:11:22 +00001064 return
Tim Peters9a8c8e22001-07-13 09:12:12 +00001065 assert len(succs[corner]) == 2
1066 assert self.coords2index(1, 2) in succs[corner]
1067 assert self.coords2index(2, 1) in succs[corner]
unknown31569562001-07-04 22:11:22 +00001068 # Only two choices. Whichever we pick, the other must be the
Tim Peters9a8c8e22001-07-13 09:12:12 +00001069 # square picked on move m*n, as it's the only way to get back
unknown31569562001-07-04 22:11:22 +00001070 # to (0, 0). Save its index in self.final so that moves before
1071 # the last know it must be kept free.
1072 for i, j in (1, 2), (2, 1):
Tim Peters9a8c8e22001-07-13 09:12:12 +00001073 this = self.coords2index(i, j)
1074 final = self.coords2index(3-i, 3-j)
unknown31569562001-07-04 22:11:22 +00001075 self.final = final
unknown31569562001-07-04 22:11:22 +00001076
Tim Peters9a8c8e22001-07-13 09:12:12 +00001077 remove_from_successors(this)
1078 succs[final].append(corner)
unknown31569562001-07-04 22:11:22 +00001079 self.lastij = this
1080 yield this
Tim Peters9a8c8e22001-07-13 09:12:12 +00001081 succs[final].remove(corner)
1082 add_to_successors(this)
unknown31569562001-07-04 22:11:22 +00001083
Tim Peters9a8c8e22001-07-13 09:12:12 +00001084 # Generate moves 3 thru m*n-1.
1085 def advance(len=len):
unknown31569562001-07-04 22:11:22 +00001086 # If some successor has only one exit, must take it.
1087 # Else favor successors with fewer exits.
1088 candidates = []
1089 for i in succs[self.lastij]:
Tim Peters9a8c8e22001-07-13 09:12:12 +00001090 e = len(succs[i])
1091 assert e > 0, "else remove_from_successors() pruning flawed"
1092 if e == 1:
1093 candidates = [(e, i)]
1094 break
1095 candidates.append((e, i))
unknown31569562001-07-04 22:11:22 +00001096 else:
1097 candidates.sort()
1098
1099 for e, i in candidates:
1100 if i != self.final:
Tim Peters9a8c8e22001-07-13 09:12:12 +00001101 if remove_from_successors(i):
unknown31569562001-07-04 22:11:22 +00001102 self.lastij = i
1103 yield i
Tim Peters9a8c8e22001-07-13 09:12:12 +00001104 add_to_successors(i)
unknown31569562001-07-04 22:11:22 +00001105
Tim Peters9a8c8e22001-07-13 09:12:12 +00001106 # Generate moves 3 thru m*n-1. Alternative version using a
unknown31569562001-07-04 22:11:22 +00001107 # stronger (but more expensive) heuristic to order successors.
Tim Peters9a8c8e22001-07-13 09:12:12 +00001108 # Since the # of backtracking levels is m*n, a poor move early on
1109 # can take eons to undo. Smallest square board for which this
1110 # matters a lot is 52x52.
1111 def advance_hard(vmid=(m-1)/2.0, hmid=(n-1)/2.0, len=len):
unknown31569562001-07-04 22:11:22 +00001112 # If some successor has only one exit, must take it.
1113 # Else favor successors with fewer exits.
1114 # Break ties via max distance from board centerpoint (favor
1115 # corners and edges whenever possible).
1116 candidates = []
1117 for i in succs[self.lastij]:
Tim Peters9a8c8e22001-07-13 09:12:12 +00001118 e = len(succs[i])
1119 assert e > 0, "else remove_from_successors() pruning flawed"
1120 if e == 1:
1121 candidates = [(e, 0, i)]
1122 break
1123 i1, j1 = self.index2coords(i)
1124 d = (i1 - vmid)**2 + (j1 - hmid)**2
1125 candidates.append((e, -d, i))
unknown31569562001-07-04 22:11:22 +00001126 else:
1127 candidates.sort()
1128
1129 for e, d, i in candidates:
1130 if i != self.final:
Tim Peters9a8c8e22001-07-13 09:12:12 +00001131 if remove_from_successors(i):
unknown31569562001-07-04 22:11:22 +00001132 self.lastij = i
1133 yield i
Tim Peters9a8c8e22001-07-13 09:12:12 +00001134 add_to_successors(i)
unknown31569562001-07-04 22:11:22 +00001135
1136 # Generate the last move.
1137 def last():
1138 assert self.final in succs[self.lastij]
1139 yield self.final
1140
Tim Peters9a8c8e22001-07-13 09:12:12 +00001141 if m*n < 4:
1142 self.squaregenerators = [first]
unknown31569562001-07-04 22:11:22 +00001143 else:
Tim Peters9a8c8e22001-07-13 09:12:12 +00001144 self.squaregenerators = [first, second] + \
1145 [hard and advance_hard or advance] * (m*n - 3) + \
unknown31569562001-07-04 22:11:22 +00001146 [last]
1147
Tim Peters9a8c8e22001-07-13 09:12:12 +00001148 def coords2index(self, i, j):
1149 assert 0 <= i < self.m
1150 assert 0 <= j < self.n
1151 return i * self.n + j
1152
1153 def index2coords(self, index):
1154 assert 0 <= index < self.m * self.n
1155 return divmod(index, self.n)
1156
1157 def _init_board(self):
1158 succs = self.succs
1159 del succs[:]
1160 m, n = self.m, self.n
1161 c2i = self.coords2index
1162
1163 offsets = [( 1, 2), ( 2, 1), ( 2, -1), ( 1, -2),
1164 (-1, -2), (-2, -1), (-2, 1), (-1, 2)]
1165 rangen = range(n)
1166 for i in range(m):
1167 for j in rangen:
1168 s = [c2i(i+io, j+jo) for io, jo in offsets
1169 if 0 <= i+io < m and
1170 0 <= j+jo < n]
1171 succs.append(s)
1172
unknown31569562001-07-04 22:11:22 +00001173 # Generate solutions.
1174 def solve(self):
Tim Peters9a8c8e22001-07-13 09:12:12 +00001175 self._init_board()
1176 for x in conjoin(self.squaregenerators):
unknown31569562001-07-04 22:11:22 +00001177 yield x
1178
1179 def printsolution(self, x):
Tim Peters9a8c8e22001-07-13 09:12:12 +00001180 m, n = self.m, self.n
1181 assert len(x) == m*n
1182 w = len(str(m*n))
unknown31569562001-07-04 22:11:22 +00001183 format = "%" + str(w) + "d"
1184
Tim Peters9a8c8e22001-07-13 09:12:12 +00001185 squares = [[None] * n for i in range(m)]
unknown31569562001-07-04 22:11:22 +00001186 k = 1
1187 for i in x:
Tim Peters9a8c8e22001-07-13 09:12:12 +00001188 i1, j1 = self.index2coords(i)
unknown31569562001-07-04 22:11:22 +00001189 squares[i1][j1] = format % k
1190 k += 1
1191
1192 sep = "+" + ("-" * w + "+") * n
1193 print sep
Tim Peters9a8c8e22001-07-13 09:12:12 +00001194 for i in range(m):
unknown31569562001-07-04 22:11:22 +00001195 row = squares[i]
1196 print "|" + "|".join(row) + "|"
1197 print sep
1198
Tim Petersbe4f0a72001-06-29 02:41:16 +00001199conjoin_tests = """
1200
1201Generate the 3-bit binary numbers in order. This illustrates dumbest-
1202possible use of conjoin, just to generate the full cross-product.
1203
unknown31569562001-07-04 22:11:22 +00001204>>> for c in conjoin([lambda: iter((0, 1))] * 3):
Tim Petersbe4f0a72001-06-29 02:41:16 +00001205... print c
1206[0, 0, 0]
1207[0, 0, 1]
1208[0, 1, 0]
1209[0, 1, 1]
1210[1, 0, 0]
1211[1, 0, 1]
1212[1, 1, 0]
1213[1, 1, 1]
1214
Tim Petersc468fd22001-06-30 07:29:44 +00001215For efficiency in typical backtracking apps, conjoin() yields the same list
1216object each time. So if you want to save away a full account of its
1217generated sequence, you need to copy its results.
1218
1219>>> def gencopy(iterator):
1220... for x in iterator:
1221... yield x[:]
1222
1223>>> for n in range(10):
unknown31569562001-07-04 22:11:22 +00001224... all = list(gencopy(conjoin([lambda: iter((0, 1))] * n)))
Tim Petersc468fd22001-06-30 07:29:44 +00001225... print n, len(all), all[0] == [0] * n, all[-1] == [1] * n
12260 1 1 1
12271 2 1 1
12282 4 1 1
12293 8 1 1
12304 16 1 1
12315 32 1 1
12326 64 1 1
12337 128 1 1
12348 256 1 1
12359 512 1 1
1236
Tim Petersbe4f0a72001-06-29 02:41:16 +00001237And run an 8-queens solver.
1238
1239>>> q = Queens(8)
1240>>> LIMIT = 2
1241>>> count = 0
1242>>> for row2col in q.solve():
1243... count += 1
1244... if count <= LIMIT:
1245... print "Solution", count
1246... q.printsolution(row2col)
1247Solution 1
1248+-+-+-+-+-+-+-+-+
1249|Q| | | | | | | |
1250+-+-+-+-+-+-+-+-+
1251| | | | |Q| | | |
1252+-+-+-+-+-+-+-+-+
1253| | | | | | | |Q|
1254+-+-+-+-+-+-+-+-+
1255| | | | | |Q| | |
1256+-+-+-+-+-+-+-+-+
1257| | |Q| | | | | |
1258+-+-+-+-+-+-+-+-+
1259| | | | | | |Q| |
1260+-+-+-+-+-+-+-+-+
1261| |Q| | | | | | |
1262+-+-+-+-+-+-+-+-+
1263| | | |Q| | | | |
1264+-+-+-+-+-+-+-+-+
1265Solution 2
1266+-+-+-+-+-+-+-+-+
1267|Q| | | | | | | |
1268+-+-+-+-+-+-+-+-+
1269| | | | | |Q| | |
1270+-+-+-+-+-+-+-+-+
1271| | | | | | | |Q|
1272+-+-+-+-+-+-+-+-+
1273| | |Q| | | | | |
1274+-+-+-+-+-+-+-+-+
1275| | | | | | |Q| |
1276+-+-+-+-+-+-+-+-+
1277| | | |Q| | | | |
1278+-+-+-+-+-+-+-+-+
1279| |Q| | | | | | |
1280+-+-+-+-+-+-+-+-+
1281| | | | |Q| | | |
1282+-+-+-+-+-+-+-+-+
1283
1284>>> print count, "solutions in all."
128592 solutions in all.
unknown31569562001-07-04 22:11:22 +00001286
1287And run a Knight's Tour on a 10x10 board. Note that there are about
128820,000 solutions even on a 6x6 board, so don't dare run this to exhaustion.
1289
Tim Peters9a8c8e22001-07-13 09:12:12 +00001290>>> k = Knights(10, 10)
unknown31569562001-07-04 22:11:22 +00001291>>> LIMIT = 2
1292>>> count = 0
1293>>> for x in k.solve():
1294... count += 1
1295... if count <= LIMIT:
1296... print "Solution", count
1297... k.printsolution(x)
1298... else:
1299... break
1300Solution 1
1301+---+---+---+---+---+---+---+---+---+---+
1302| 1| 58| 27| 34| 3| 40| 29| 10| 5| 8|
1303+---+---+---+---+---+---+---+---+---+---+
1304| 26| 35| 2| 57| 28| 33| 4| 7| 30| 11|
1305+---+---+---+---+---+---+---+---+---+---+
1306| 59|100| 73| 36| 41| 56| 39| 32| 9| 6|
1307+---+---+---+---+---+---+---+---+---+---+
1308| 74| 25| 60| 55| 72| 37| 42| 49| 12| 31|
1309+---+---+---+---+---+---+---+---+---+---+
1310| 61| 86| 99| 76| 63| 52| 47| 38| 43| 50|
1311+---+---+---+---+---+---+---+---+---+---+
1312| 24| 75| 62| 85| 54| 71| 64| 51| 48| 13|
1313+---+---+---+---+---+---+---+---+---+---+
1314| 87| 98| 91| 80| 77| 84| 53| 46| 65| 44|
1315+---+---+---+---+---+---+---+---+---+---+
1316| 90| 23| 88| 95| 70| 79| 68| 83| 14| 17|
1317+---+---+---+---+---+---+---+---+---+---+
1318| 97| 92| 21| 78| 81| 94| 19| 16| 45| 66|
1319+---+---+---+---+---+---+---+---+---+---+
1320| 22| 89| 96| 93| 20| 69| 82| 67| 18| 15|
1321+---+---+---+---+---+---+---+---+---+---+
1322Solution 2
1323+---+---+---+---+---+---+---+---+---+---+
1324| 1| 58| 27| 34| 3| 40| 29| 10| 5| 8|
1325+---+---+---+---+---+---+---+---+---+---+
1326| 26| 35| 2| 57| 28| 33| 4| 7| 30| 11|
1327+---+---+---+---+---+---+---+---+---+---+
1328| 59|100| 73| 36| 41| 56| 39| 32| 9| 6|
1329+---+---+---+---+---+---+---+---+---+---+
1330| 74| 25| 60| 55| 72| 37| 42| 49| 12| 31|
1331+---+---+---+---+---+---+---+---+---+---+
1332| 61| 86| 99| 76| 63| 52| 47| 38| 43| 50|
1333+---+---+---+---+---+---+---+---+---+---+
1334| 24| 75| 62| 85| 54| 71| 64| 51| 48| 13|
1335+---+---+---+---+---+---+---+---+---+---+
1336| 87| 98| 89| 80| 77| 84| 53| 46| 65| 44|
1337+---+---+---+---+---+---+---+---+---+---+
1338| 90| 23| 92| 95| 70| 79| 68| 83| 14| 17|
1339+---+---+---+---+---+---+---+---+---+---+
1340| 97| 88| 21| 78| 81| 94| 19| 16| 45| 66|
1341+---+---+---+---+---+---+---+---+---+---+
1342| 22| 91| 96| 93| 20| 69| 82| 67| 18| 15|
1343+---+---+---+---+---+---+---+---+---+---+
Tim Petersbe4f0a72001-06-29 02:41:16 +00001344"""
1345
Tim Petersf6ed0742001-06-27 07:17:57 +00001346__test__ = {"tut": tutorial_tests,
1347 "pep": pep_tests,
1348 "email": email_tests,
1349 "fun": fun_tests,
Tim Petersbe4f0a72001-06-29 02:41:16 +00001350 "syntax": syntax_tests,
1351 "conjoin": conjoin_tests}
Tim Peters1def3512001-06-23 20:27:04 +00001352
1353# Magic test name that regrtest.py invokes *after* importing this module.
1354# This worms around a bootstrap problem.
1355# Note that doctest and regrtest both look in sys.argv for a "-v" argument,
1356# so this works as expected in both ways of running regrtest.
1357def test_main():
1358 import doctest, test_generators
Tim Petersa1d54552001-07-12 22:55:42 +00001359 if 0: # change to 1 to run forever (to check for leaks)
1360 while 1:
Tim Peters2106ef02001-06-25 01:30:12 +00001361 doctest.master = None
1362 doctest.testmod(test_generators)
Tim Petersa1d54552001-07-12 22:55:42 +00001363 print ".",
Tim Peters2106ef02001-06-25 01:30:12 +00001364 else:
1365 doctest.testmod(test_generators)
Tim Peters1def3512001-06-23 20:27:04 +00001366
1367# This part isn't needed for regrtest, but for running the test directly.
1368if __name__ == "__main__":
1369 test_main()