blob: 41629d352741dfa9baadf29f0e79b6356c395d8e [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
Tim Peterse5614632001-08-15 04:41:19 +0000140Specification: Yield
141
142 Restriction: A generator cannot be resumed while it is actively
143 running:
144
145 >>> def g():
146 ... i = me.next()
147 ... yield i
148 >>> me = g()
149 >>> me.next()
150 Traceback (most recent call last):
151 ...
152 File "<string>", line 2, in g
153 ValueError: generator already executing
154
Tim Peters6ba5f792001-06-23 20:45:43 +0000155Specification: Return
156
157 Note that return isn't always equivalent to raising StopIteration: the
158 difference lies in how enclosing try/except constructs are treated.
159 For example,
160
161 >>> def f1():
162 ... try:
163 ... return
164 ... except:
165 ... yield 1
166 >>> print list(f1())
167 []
168
169 because, as in any function, return simply exits, but
170
171 >>> def f2():
172 ... try:
173 ... raise StopIteration
174 ... except:
175 ... yield 42
176 >>> print list(f2())
177 [42]
178
179 because StopIteration is captured by a bare "except", as is any
180 exception.
181
182Specification: Generators and Exception Propagation
183
184 >>> def f():
185 ... return 1/0
186 >>> def g():
187 ... yield f() # the zero division exception propagates
188 ... yield 42 # and we'll never get here
189 >>> k = g()
190 >>> k.next()
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 ?
199 StopIteration
200 >>>
201
202Specification: Try/Except/Finally
203
204 >>> def f():
205 ... try:
206 ... yield 1
207 ... try:
208 ... yield 2
209 ... 1/0
210 ... yield 3 # never get here
211 ... except ZeroDivisionError:
212 ... yield 4
213 ... yield 5
214 ... raise
215 ... except:
216 ... yield 6
217 ... yield 7 # the "raise" above stops this
218 ... except:
219 ... yield 8
220 ... yield 9
221 ... try:
222 ... x = 12
223 ... finally:
224 ... yield 10
225 ... yield 11
226 >>> print list(f())
227 [1, 2, 4, 5, 8, 9, 10, 11]
228 >>>
229
Tim Peters6ba5f792001-06-23 20:45:43 +0000230Guido's binary tree example.
231
232 >>> # A binary tree class.
233 >>> class Tree:
234 ...
235 ... def __init__(self, label, left=None, right=None):
236 ... self.label = label
237 ... self.left = left
238 ... self.right = right
239 ...
240 ... def __repr__(self, level=0, indent=" "):
241 ... s = level*indent + `self.label`
242 ... if self.left:
243 ... s = s + "\\n" + self.left.__repr__(level+1, indent)
244 ... if self.right:
245 ... s = s + "\\n" + self.right.__repr__(level+1, indent)
246 ... return s
247 ...
248 ... def __iter__(self):
249 ... return inorder(self)
250
251 >>> # Create a Tree from a list.
252 >>> def tree(list):
253 ... n = len(list)
254 ... if n == 0:
255 ... return []
256 ... i = n / 2
257 ... return Tree(list[i], tree(list[:i]), tree(list[i+1:]))
258
259 >>> # Show it off: create a tree.
260 >>> t = tree("ABCDEFGHIJKLMNOPQRSTUVWXYZ")
261
262 >>> # A recursive generator that generates Tree leaves in in-order.
263 >>> def inorder(t):
264 ... if t:
265 ... for x in inorder(t.left):
266 ... yield x
267 ... yield t.label
268 ... for x in inorder(t.right):
269 ... yield x
270
271 >>> # Show it off: create a tree.
272 ... t = tree("ABCDEFGHIJKLMNOPQRSTUVWXYZ")
273 ... # Print the nodes of the tree in in-order.
274 ... for x in t:
275 ... print x,
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
277
278 >>> # A non-recursive generator.
279 >>> def inorder(node):
280 ... stack = []
281 ... while node:
282 ... while node.left:
283 ... stack.append(node)
284 ... node = node.left
285 ... yield node.label
286 ... while not node.right:
287 ... try:
288 ... node = stack.pop()
289 ... except IndexError:
290 ... return
291 ... yield node.label
292 ... node = node.right
293
294 >>> # Exercise the non-recursive generator.
295 >>> for x in t:
296 ... print x,
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
298
299"""
300
Tim Petersb2bc6a92001-06-24 10:14:27 +0000301# Examples from Iterator-List and Python-Dev and c.l.py.
Tim Peters6ba5f792001-06-23 20:45:43 +0000302
303email_tests = """
304
305The difference between yielding None and returning it.
306
307>>> def g():
308... for i in range(3):
309... yield None
310... yield None
311... return
312>>> list(g())
313[None, None, None, None]
314
315Ensure that explicitly raising StopIteration acts like any other exception
316in try/except, not like a return.
317
318>>> def g():
319... yield 1
320... try:
321... raise StopIteration
322... except:
323... yield 2
324... yield 3
325>>> list(g())
326[1, 2, 3]
Tim Petersb9e9ff12001-06-24 03:44:52 +0000327
Tim Petersb2bc6a92001-06-24 10:14:27 +0000328Next one was posted to c.l.py.
329
330>>> def gcomb(x, k):
331... "Generate all combinations of k elements from list x."
332...
333... if k > len(x):
334... return
335... if k == 0:
336... yield []
337... else:
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)
343... yield c
344... # If it doesn't contain first, it's a k comb of rest.
345... for c in gcomb(rest, k):
346... yield c
347
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):
352... print " ", c
3530-combs of [1, 2, 3, 4]:
354 []
3551-combs of [1, 2, 3, 4]:
356 [1]
357 [2]
358 [3]
359 [4]
3602-combs of [1, 2, 3, 4]:
361 [1, 2]
362 [1, 3]
363 [1, 4]
364 [2, 3]
365 [2, 4]
366 [3, 4]
3673-combs of [1, 2, 3, 4]:
368 [1, 2, 3]
369 [1, 2, 4]
370 [1, 3, 4]
371 [2, 3, 4]
3724-combs of [1, 2, 3, 4]:
373 [1, 2, 3, 4]
3745-combs of [1, 2, 3, 4]:
Tim Peters3e7b1a02001-06-25 19:46:25 +0000375
Tim Peterse77f2e22001-06-26 22:24:51 +0000376From the Iterators list, about the types of these things.
Tim Peters3e7b1a02001-06-25 19:46:25 +0000377
378>>> def g():
379... yield 1
380...
381>>> type(g)
382<type 'function'>
383>>> i = g()
384>>> type(i)
385<type 'generator'>
Tim Peters6d6c1a32001-08-02 04:15:00 +0000386
387XXX dir(object) *generally* doesn't return useful stuff in descr-branch.
Tim Peters3e7b1a02001-06-25 19:46:25 +0000388>>> dir(i)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000389[]
390
391Was hoping to see this instead:
Tim Peterse77f2e22001-06-26 22:24:51 +0000392['gi_frame', 'gi_running', 'next']
Tim Peters6d6c1a32001-08-02 04:15:00 +0000393
Tim Peters3e7b1a02001-06-25 19:46:25 +0000394>>> print i.next.__doc__
Tim Peters6d6c1a32001-08-02 04:15:00 +0000395x.next() -> the next value, or raise StopIteration
Tim Peters3e7b1a02001-06-25 19:46:25 +0000396>>> iter(i) is i
3971
398>>> import types
399>>> isinstance(i, types.GeneratorType)
4001
Tim Peterse77f2e22001-06-26 22:24:51 +0000401
402And more, added later.
403
404>>> i.gi_running
4050
406>>> type(i.gi_frame)
407<type 'frame'>
408>>> i.gi_running = 42
409Traceback (most recent call last):
410 ...
Guido van Rossum61cf7802001-08-10 21:25:24 +0000411TypeError: readonly attribute
Tim Peterse77f2e22001-06-26 22:24:51 +0000412>>> def g():
413... yield me.gi_running
414>>> me = g()
415>>> me.gi_running
4160
417>>> me.next()
4181
419>>> me.gi_running
4200
Tim Peters35302662001-07-02 01:38:33 +0000421
422A clever union-find implementation from c.l.py, due to David Eppstein.
423Sent: Friday, June 29, 2001 12:16 PM
424To: python-list@python.org
425Subject: Re: PEP 255: Simple Generators
426
427>>> class disjointSet:
428... def __init__(self, name):
429... self.name = name
430... self.parent = None
431... self.generator = self.generate()
432...
433... def generate(self):
434... while not self.parent:
435... yield self
436... for x in self.parent.generator:
437... yield x
438...
439... def find(self):
440... return self.generator.next()
441...
442... def union(self, parent):
443... if self.parent:
444... raise ValueError("Sorry, I'm not a root!")
445... self.parent = parent
446...
447... def __str__(self):
448... return self.name
Tim Peters35302662001-07-02 01:38:33 +0000449
450>>> names = "ABCDEFGHIJKLM"
451>>> sets = [disjointSet(name) for name in names]
452>>> roots = sets[:]
453
454>>> import random
455>>> random.seed(42)
456>>> while 1:
457... for s in sets:
458... print "%s->%s" % (s, s.find()),
459... print
460... if len(roots) > 1:
461... s1 = random.choice(roots)
462... roots.remove(s1)
463... s2 = random.choice(roots)
464... s1.union(s2)
465... print "merged", s1, "into", s2
466... else:
467... break
468A->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
469merged D into G
470A->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
471merged C into F
472A->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
473merged L into A
474A->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
475merged H into E
476A->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
477merged B into E
478A->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
479merged J into G
480A->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
481merged E into G
482A->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
483merged M into G
484A->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
485merged I into K
486A->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
487merged K into A
488A->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
489merged F into A
490A->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
491merged A into G
492A->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 +0000493"""
494
Tim Peters0f9da0a2001-06-23 21:01:47 +0000495# Fun tests (for sufficiently warped notions of "fun").
496
497fun_tests = """
498
499Build up to a recursive Sieve of Eratosthenes generator.
500
501>>> def firstn(g, n):
502... return [g.next() for i in range(n)]
503
504>>> def intsfrom(i):
505... while 1:
506... yield i
507... i += 1
508
509>>> firstn(intsfrom(5), 7)
510[5, 6, 7, 8, 9, 10, 11]
511
512>>> def exclude_multiples(n, ints):
513... for i in ints:
514... if i % n:
515... yield i
516
517>>> firstn(exclude_multiples(3, intsfrom(1)), 6)
518[1, 2, 4, 5, 7, 8]
519
520>>> def sieve(ints):
521... prime = ints.next()
522... yield prime
523... not_divisible_by_prime = exclude_multiples(prime, ints)
524... for p in sieve(not_divisible_by_prime):
525... yield p
526
527>>> primes = sieve(intsfrom(2))
528>>> firstn(primes, 20)
529[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 +0000530
Tim Petersf6ed0742001-06-27 07:17:57 +0000531
Tim Petersb9e9ff12001-06-24 03:44:52 +0000532Another famous problem: generate all integers of the form
533 2**i * 3**j * 5**k
534in increasing order, where i,j,k >= 0. Trickier than it may look at first!
535Try writing it without generators, and correctly, and without generating
5363 internal results for each result output.
537
538>>> def times(n, g):
539... for i in g:
540... yield n * i
541>>> firstn(times(10, intsfrom(1)), 10)
542[10, 20, 30, 40, 50, 60, 70, 80, 90, 100]
543
544>>> def merge(g, h):
545... ng = g.next()
546... nh = h.next()
547... while 1:
548... if ng < nh:
549... yield ng
550... ng = g.next()
551... elif ng > nh:
552... yield nh
553... nh = h.next()
554... else:
555... yield ng
556... ng = g.next()
557... nh = h.next()
558
Tim Petersf6ed0742001-06-27 07:17:57 +0000559The following works, but is doing a whale of a lot of redundant work --
560it's not clear how to get the internal uses of m235 to share a single
561generator. Note that me_times2 (etc) each need to see every element in the
562result sequence. So this is an example where lazy lists are more natural
563(you can look at the head of a lazy list any number of times).
Tim Petersb9e9ff12001-06-24 03:44:52 +0000564
565>>> def m235():
566... yield 1
567... me_times2 = times(2, m235())
568... me_times3 = times(3, m235())
569... me_times5 = times(5, m235())
570... for i in merge(merge(me_times2,
571... me_times3),
572... me_times5):
573... yield i
574
Tim Petersf6ed0742001-06-27 07:17:57 +0000575Don't print "too many" of these -- the implementation above is extremely
576inefficient: each call of m235() leads to 3 recursive calls, and in
577turn each of those 3 more, and so on, and so on, until we've descended
578enough levels to satisfy the print stmts. Very odd: when I printed 5
579lines of results below, this managed to screw up Win98's malloc in "the
580usual" way, i.e. the heap grew over 4Mb so Win98 started fragmenting
581address space, and it *looked* like a very slow leak.
582
Tim Petersb9e9ff12001-06-24 03:44:52 +0000583>>> result = m235()
Tim Petersf6ed0742001-06-27 07:17:57 +0000584>>> for i in range(3):
Tim Petersb9e9ff12001-06-24 03:44:52 +0000585... print firstn(result, 15)
586[1, 2, 3, 4, 5, 6, 8, 9, 10, 12, 15, 16, 18, 20, 24]
587[25, 27, 30, 32, 36, 40, 45, 48, 50, 54, 60, 64, 72, 75, 80]
588[81, 90, 96, 100, 108, 120, 125, 128, 135, 144, 150, 160, 162, 180, 192]
Tim Petersee309272001-06-24 05:47:06 +0000589
590Heh. Here's one way to get a shared list, complete with an excruciating
591namespace renaming trick. The *pretty* part is that the times() and merge()
592functions can be reused as-is, because they only assume their stream
593arguments are iterable -- a LazyList is the same as a generator to times().
594
595>>> class LazyList:
596... def __init__(self, g):
597... self.sofar = []
598... self.fetch = g.next
599...
600... def __getitem__(self, i):
601... sofar, fetch = self.sofar, self.fetch
602... while i >= len(sofar):
603... sofar.append(fetch())
604... return sofar[i]
605
606>>> def m235():
607... yield 1
Tim Petersea2e97a2001-06-24 07:10:02 +0000608... # Gack: m235 below actually refers to a LazyList.
Tim Petersee309272001-06-24 05:47:06 +0000609... me_times2 = times(2, m235)
610... me_times3 = times(3, m235)
611... me_times5 = times(5, m235)
612... for i in merge(merge(me_times2,
613... me_times3),
614... me_times5):
615... yield i
616
Tim Petersf6ed0742001-06-27 07:17:57 +0000617Print as many of these as you like -- *this* implementation is memory-
Neil Schemenauerb20e9db2001-07-12 13:26:41 +0000618efficient.
Tim Petersf6ed0742001-06-27 07:17:57 +0000619
Tim Petersee309272001-06-24 05:47:06 +0000620>>> m235 = LazyList(m235())
621>>> for i in range(5):
622... print [m235[j] for j in range(15*i, 15*(i+1))]
623[1, 2, 3, 4, 5, 6, 8, 9, 10, 12, 15, 16, 18, 20, 24]
624[25, 27, 30, 32, 36, 40, 45, 48, 50, 54, 60, 64, 72, 75, 80]
625[81, 90, 96, 100, 108, 120, 125, 128, 135, 144, 150, 160, 162, 180, 192]
626[200, 216, 225, 240, 243, 250, 256, 270, 288, 300, 320, 324, 360, 375, 384]
627[400, 405, 432, 450, 480, 486, 500, 512, 540, 576, 600, 625, 640, 648, 675]
Tim Petersf6ed0742001-06-27 07:17:57 +0000628
Tim Petersf6ed0742001-06-27 07:17:57 +0000629
630Ye olde Fibonacci generator, LazyList style.
631
632>>> def fibgen(a, b):
633...
634... def sum(g, h):
635... while 1:
636... yield g.next() + h.next()
637...
638... def tail(g):
639... g.next() # throw first away
640... for x in g:
641... yield x
642...
643... yield a
644... yield b
645... for s in sum(iter(fib),
646... tail(iter(fib))):
647... yield s
648
649>>> fib = LazyList(fibgen(1, 2))
650>>> firstn(iter(fib), 17)
651[1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597, 2584]
Tim Peters0f9da0a2001-06-23 21:01:47 +0000652"""
653
Tim Petersb6c3cea2001-06-26 03:36:28 +0000654# syntax_tests mostly provokes SyntaxErrors. Also fiddling with #if 0
655# hackery.
Tim Petersee309272001-06-24 05:47:06 +0000656
Tim Petersea2e97a2001-06-24 07:10:02 +0000657syntax_tests = """
658
659>>> def f():
660... return 22
661... yield 1
662Traceback (most recent call last):
663 ...
664SyntaxError: 'return' with argument inside generator (<string>, line 2)
665
666>>> def f():
667... yield 1
668... return 22
669Traceback (most recent call last):
670 ...
671SyntaxError: 'return' with argument inside generator (<string>, line 3)
672
673"return None" is not the same as "return" in a generator:
674
675>>> def f():
676... yield 1
677... return None
678Traceback (most recent call last):
679 ...
680SyntaxError: 'return' with argument inside generator (<string>, line 3)
681
682This one is fine:
683
684>>> def f():
685... yield 1
686... return
687
688>>> def f():
689... try:
690... yield 1
691... finally:
692... pass
693Traceback (most recent call last):
694 ...
695SyntaxError: 'yield' not allowed in a 'try' block with a 'finally' clause (<string>, line 3)
696
697>>> def f():
698... try:
699... try:
700... 1/0
701... except ZeroDivisionError:
702... yield 666 # bad because *outer* try has finally
703... except:
704... pass
705... finally:
706... pass
707Traceback (most recent call last):
708 ...
709SyntaxError: 'yield' not allowed in a 'try' block with a 'finally' clause (<string>, line 6)
710
711But this is fine:
712
713>>> def f():
714... try:
715... try:
716... yield 12
717... 1/0
718... except ZeroDivisionError:
719... yield 666
720... except:
721... try:
722... x = 12
723... finally:
724... yield 12
725... except:
726... return
727>>> list(f())
728[12, 666]
Tim Petersb6c3cea2001-06-26 03:36:28 +0000729
730>>> def f():
Tim Peters08a898f2001-06-28 01:52:22 +0000731... yield
732Traceback (most recent call last):
733SyntaxError: invalid syntax
734
735>>> def f():
736... if 0:
737... yield
738Traceback (most recent call last):
739SyntaxError: invalid syntax
740
741>>> def f():
Tim Petersb6c3cea2001-06-26 03:36:28 +0000742... if 0:
743... yield 1
744>>> type(f())
745<type 'generator'>
746
747>>> def f():
748... if "":
749... yield None
750>>> type(f())
751<type 'generator'>
752
753>>> def f():
754... return
755... try:
756... if x==4:
757... pass
758... elif 0:
759... try:
760... 1/0
761... except SyntaxError:
762... pass
763... else:
764... if 0:
765... while 12:
766... x += 1
767... yield 2 # don't blink
768... f(a, b, c, d, e)
769... else:
770... pass
771... except:
772... x = 1
773... return
774>>> type(f())
775<type 'generator'>
776
777>>> def f():
778... if 0:
779... def g():
780... yield 1
781...
782>>> type(f())
783<type 'None'>
784
785>>> def f():
786... if 0:
787... class C:
788... def __init__(self):
789... yield 1
790... def f(self):
791... yield 2
792>>> type(f())
793<type 'None'>
Tim Peters08a898f2001-06-28 01:52:22 +0000794
795>>> def f():
796... if 0:
797... return
798... if 0:
799... yield 2
800>>> type(f())
801<type 'generator'>
802
803
804>>> def f():
805... if 0:
806... lambda x: x # shouldn't trigger here
807... return # or here
808... def f(i):
809... return 2*i # or here
810... if 0:
811... return 3 # but *this* sucks (line 8)
812... if 0:
813... yield 2 # because it's a generator
814Traceback (most recent call last):
815SyntaxError: 'return' with argument inside generator (<string>, line 8)
Tim Petersea2e97a2001-06-24 07:10:02 +0000816"""
817
Tim Petersbe4f0a72001-06-29 02:41:16 +0000818# conjoin is a simple backtracking generator, named in honor of Icon's
819# "conjunction" control structure. Pass a list of no-argument functions
820# that return iterable objects. Easiest to explain by example: assume the
821# function list [x, y, z] is passed. Then conjoin acts like:
822#
823# def g():
824# values = [None] * 3
825# for values[0] in x():
826# for values[1] in y():
827# for values[2] in z():
828# yield values
829#
830# So some 3-lists of values *may* be generated, each time we successfully
831# get into the innermost loop. If an iterator fails (is exhausted) before
832# then, it "backtracks" to get the next value from the nearest enclosing
833# iterator (the one "to the left"), and starts all over again at the next
834# slot (pumps a fresh iterator). Of course this is most useful when the
835# iterators have side-effects, so that which values *can* be generated at
836# each slot depend on the values iterated at previous slots.
837
838def conjoin(gs):
839
840 values = [None] * len(gs)
841
842 def gen(i, values=values):
843 if i >= len(gs):
844 yield values
845 else:
846 for values[i] in gs[i]():
847 for x in gen(i+1):
848 yield x
849
850 for x in gen(0):
851 yield x
852
Tim Petersc468fd22001-06-30 07:29:44 +0000853# That works fine, but recursing a level and checking i against len(gs) for
854# each item produced is inefficient. By doing manual loop unrolling across
855# generator boundaries, it's possible to eliminate most of that overhead.
856# This isn't worth the bother *in general* for generators, but conjoin() is
857# a core building block for some CPU-intensive generator applications.
858
859def conjoin(gs):
860
861 n = len(gs)
862 values = [None] * n
863
864 # Do one loop nest at time recursively, until the # of loop nests
865 # remaining is divisible by 3.
866
867 def gen(i, values=values):
868 if i >= n:
869 yield values
870
871 elif (n-i) % 3:
872 ip1 = i+1
873 for values[i] in gs[i]():
874 for x in gen(ip1):
875 yield x
876
877 else:
878 for x in _gen3(i):
879 yield x
880
881 # Do three loop nests at a time, recursing only if at least three more
882 # remain. Don't call directly: this is an internal optimization for
883 # gen's use.
884
885 def _gen3(i, values=values):
886 assert i < n and (n-i) % 3 == 0
887 ip1, ip2, ip3 = i+1, i+2, i+3
888 g, g1, g2 = gs[i : ip3]
889
890 if ip3 >= n:
891 # These are the last three, so we can yield values directly.
892 for values[i] in g():
893 for values[ip1] in g1():
894 for values[ip2] in g2():
895 yield values
896
897 else:
898 # At least 6 loop nests remain; peel off 3 and recurse for the
899 # rest.
900 for values[i] in g():
901 for values[ip1] in g1():
902 for values[ip2] in g2():
903 for x in _gen3(ip3):
904 yield x
905
906 for x in gen(0):
907 yield x
908
unknown31569562001-07-04 22:11:22 +0000909# And one more approach: For backtracking apps like the Knight's Tour
910# solver below, the number of backtracking levels can be enormous (one
911# level per square, for the Knight's Tour, so that e.g. a 100x100 board
912# needs 10,000 levels). In such cases Python is likely to run out of
913# stack space due to recursion. So here's a recursion-free version of
914# conjoin too.
915# NOTE WELL: This allows large problems to be solved with only trivial
916# demands on stack space. Without explicitly resumable generators, this is
Tim Peters9a8c8e22001-07-13 09:12:12 +0000917# much harder to achieve. OTOH, this is much slower (up to a factor of 2)
918# than the fancy unrolled recursive conjoin.
unknown31569562001-07-04 22:11:22 +0000919
920def flat_conjoin(gs): # rename to conjoin to run tests with this instead
921 n = len(gs)
922 values = [None] * n
923 iters = [None] * n
Tim Peters9a8c8e22001-07-13 09:12:12 +0000924 _StopIteration = StopIteration # make local because caught a *lot*
unknown31569562001-07-04 22:11:22 +0000925 i = 0
Tim Peters9a8c8e22001-07-13 09:12:12 +0000926 while 1:
927 # Descend.
928 try:
929 while i < n:
930 it = iters[i] = gs[i]().next
931 values[i] = it()
932 i += 1
933 except _StopIteration:
934 pass
unknown31569562001-07-04 22:11:22 +0000935 else:
Tim Peters9a8c8e22001-07-13 09:12:12 +0000936 assert i == n
937 yield values
unknown31569562001-07-04 22:11:22 +0000938
Tim Peters9a8c8e22001-07-13 09:12:12 +0000939 # Backtrack until an older iterator can be resumed.
940 i -= 1
unknown31569562001-07-04 22:11:22 +0000941 while i >= 0:
942 try:
943 values[i] = iters[i]()
Tim Peters9a8c8e22001-07-13 09:12:12 +0000944 # Success! Start fresh at next level.
unknown31569562001-07-04 22:11:22 +0000945 i += 1
946 break
Tim Peters9a8c8e22001-07-13 09:12:12 +0000947 except _StopIteration:
948 # Continue backtracking.
949 i -= 1
950 else:
951 assert i < 0
952 break
unknown31569562001-07-04 22:11:22 +0000953
Tim Petersbe4f0a72001-06-29 02:41:16 +0000954# A conjoin-based N-Queens solver.
955
956class Queens:
957 def __init__(self, n):
958 self.n = n
959 rangen = range(n)
960
961 # Assign a unique int to each column and diagonal.
962 # columns: n of those, range(n).
963 # NW-SE diagonals: 2n-1 of these, i-j unique and invariant along
964 # each, smallest i-j is 0-(n-1) = 1-n, so add n-1 to shift to 0-
965 # based.
966 # NE-SW diagonals: 2n-1 of these, i+j unique and invariant along
967 # each, smallest i+j is 0, largest is 2n-2.
968
969 # For each square, compute a bit vector of the columns and
970 # diagonals it covers, and for each row compute a function that
971 # generates the possiblities for the columns in that row.
972 self.rowgenerators = []
973 for i in rangen:
974 rowuses = [(1L << j) | # column ordinal
975 (1L << (n + i-j + n-1)) | # NW-SE ordinal
976 (1L << (n + 2*n-1 + i+j)) # NE-SW ordinal
977 for j in rangen]
978
979 def rowgen(rowuses=rowuses):
980 for j in rangen:
981 uses = rowuses[j]
Tim Petersc468fd22001-06-30 07:29:44 +0000982 if uses & self.used == 0:
983 self.used |= uses
984 yield j
985 self.used &= ~uses
Tim Petersbe4f0a72001-06-29 02:41:16 +0000986
987 self.rowgenerators.append(rowgen)
988
989 # Generate solutions.
990 def solve(self):
991 self.used = 0
992 for row2col in conjoin(self.rowgenerators):
993 yield row2col
994
995 def printsolution(self, row2col):
996 n = self.n
997 assert n == len(row2col)
998 sep = "+" + "-+" * n
999 print sep
1000 for i in range(n):
1001 squares = [" " for j in range(n)]
1002 squares[row2col[i]] = "Q"
1003 print "|" + "|".join(squares) + "|"
1004 print sep
1005
unknown31569562001-07-04 22:11:22 +00001006# A conjoin-based Knight's Tour solver. This is pretty sophisticated
1007# (e.g., when used with flat_conjoin above, and passing hard=1 to the
1008# constructor, a 200x200 Knight's Tour was found quickly -- note that we're
Tim Peters9a8c8e22001-07-13 09:12:12 +00001009# creating 10s of thousands of generators then!), and is lengthy.
unknown31569562001-07-04 22:11:22 +00001010
1011class Knights:
Tim Peters9a8c8e22001-07-13 09:12:12 +00001012 def __init__(self, m, n, hard=0):
1013 self.m, self.n = m, n
unknown31569562001-07-04 22:11:22 +00001014
Tim Peters9a8c8e22001-07-13 09:12:12 +00001015 # solve() will set up succs[i] to be a list of square #i's
1016 # successors.
1017 succs = self.succs = []
unknown31569562001-07-04 22:11:22 +00001018
Tim Peters9a8c8e22001-07-13 09:12:12 +00001019 # Remove i0 from each of its successor's successor lists, i.e.
1020 # successors can't go back to i0 again. Return 0 if we can
1021 # detect this makes a solution impossible, else return 1.
unknown31569562001-07-04 22:11:22 +00001022
Tim Peters9a8c8e22001-07-13 09:12:12 +00001023 def remove_from_successors(i0, len=len):
unknown31569562001-07-04 22:11:22 +00001024 # If we remove all exits from a free square, we're dead:
1025 # even if we move to it next, we can't leave it again.
1026 # If we create a square with one exit, we must visit it next;
1027 # else somebody else will have to visit it, and since there's
1028 # only one adjacent, there won't be a way to leave it again.
1029 # Finelly, if we create more than one free square with a
1030 # single exit, we can only move to one of them next, leaving
1031 # the other one a dead end.
1032 ne0 = ne1 = 0
1033 for i in succs[i0]:
Tim Peters9a8c8e22001-07-13 09:12:12 +00001034 s = succs[i]
1035 s.remove(i0)
1036 e = len(s)
1037 if e == 0:
1038 ne0 += 1
1039 elif e == 1:
1040 ne1 += 1
unknown31569562001-07-04 22:11:22 +00001041 return ne0 == 0 and ne1 < 2
1042
Tim Peters9a8c8e22001-07-13 09:12:12 +00001043 # Put i0 back in each of its successor's successor lists.
1044
1045 def add_to_successors(i0):
unknown31569562001-07-04 22:11:22 +00001046 for i in succs[i0]:
Tim Peters9a8c8e22001-07-13 09:12:12 +00001047 succs[i].append(i0)
unknown31569562001-07-04 22:11:22 +00001048
1049 # Generate the first move.
1050 def first():
Tim Peters9a8c8e22001-07-13 09:12:12 +00001051 if m < 1 or n < 1:
unknown31569562001-07-04 22:11:22 +00001052 return
1053
unknown31569562001-07-04 22:11:22 +00001054 # Since we're looking for a cycle, it doesn't matter where we
1055 # start. Starting in a corner makes the 2nd move easy.
Tim Peters9a8c8e22001-07-13 09:12:12 +00001056 corner = self.coords2index(0, 0)
1057 remove_from_successors(corner)
unknown31569562001-07-04 22:11:22 +00001058 self.lastij = corner
1059 yield corner
Tim Peters9a8c8e22001-07-13 09:12:12 +00001060 add_to_successors(corner)
unknown31569562001-07-04 22:11:22 +00001061
1062 # Generate the second moves.
1063 def second():
Tim Peters9a8c8e22001-07-13 09:12:12 +00001064 corner = self.coords2index(0, 0)
unknown31569562001-07-04 22:11:22 +00001065 assert self.lastij == corner # i.e., we started in the corner
Tim Peters9a8c8e22001-07-13 09:12:12 +00001066 if m < 3 or n < 3:
unknown31569562001-07-04 22:11:22 +00001067 return
Tim Peters9a8c8e22001-07-13 09:12:12 +00001068 assert len(succs[corner]) == 2
1069 assert self.coords2index(1, 2) in succs[corner]
1070 assert self.coords2index(2, 1) in succs[corner]
unknown31569562001-07-04 22:11:22 +00001071 # Only two choices. Whichever we pick, the other must be the
Tim Peters9a8c8e22001-07-13 09:12:12 +00001072 # square picked on move m*n, as it's the only way to get back
unknown31569562001-07-04 22:11:22 +00001073 # to (0, 0). Save its index in self.final so that moves before
1074 # the last know it must be kept free.
1075 for i, j in (1, 2), (2, 1):
Tim Peters9a8c8e22001-07-13 09:12:12 +00001076 this = self.coords2index(i, j)
1077 final = self.coords2index(3-i, 3-j)
unknown31569562001-07-04 22:11:22 +00001078 self.final = final
unknown31569562001-07-04 22:11:22 +00001079
Tim Peters9a8c8e22001-07-13 09:12:12 +00001080 remove_from_successors(this)
1081 succs[final].append(corner)
unknown31569562001-07-04 22:11:22 +00001082 self.lastij = this
1083 yield this
Tim Peters9a8c8e22001-07-13 09:12:12 +00001084 succs[final].remove(corner)
1085 add_to_successors(this)
unknown31569562001-07-04 22:11:22 +00001086
Tim Peters9a8c8e22001-07-13 09:12:12 +00001087 # Generate moves 3 thru m*n-1.
1088 def advance(len=len):
unknown31569562001-07-04 22:11:22 +00001089 # If some successor has only one exit, must take it.
1090 # Else favor successors with fewer exits.
1091 candidates = []
1092 for i in succs[self.lastij]:
Tim Peters9a8c8e22001-07-13 09:12:12 +00001093 e = len(succs[i])
1094 assert e > 0, "else remove_from_successors() pruning flawed"
1095 if e == 1:
1096 candidates = [(e, i)]
1097 break
1098 candidates.append((e, i))
unknown31569562001-07-04 22:11:22 +00001099 else:
1100 candidates.sort()
1101
1102 for e, i in candidates:
1103 if i != self.final:
Tim Peters9a8c8e22001-07-13 09:12:12 +00001104 if remove_from_successors(i):
unknown31569562001-07-04 22:11:22 +00001105 self.lastij = i
1106 yield i
Tim Peters9a8c8e22001-07-13 09:12:12 +00001107 add_to_successors(i)
unknown31569562001-07-04 22:11:22 +00001108
Tim Peters9a8c8e22001-07-13 09:12:12 +00001109 # Generate moves 3 thru m*n-1. Alternative version using a
unknown31569562001-07-04 22:11:22 +00001110 # stronger (but more expensive) heuristic to order successors.
Tim Peters9a8c8e22001-07-13 09:12:12 +00001111 # Since the # of backtracking levels is m*n, a poor move early on
1112 # can take eons to undo. Smallest square board for which this
1113 # matters a lot is 52x52.
1114 def advance_hard(vmid=(m-1)/2.0, hmid=(n-1)/2.0, len=len):
unknown31569562001-07-04 22:11:22 +00001115 # If some successor has only one exit, must take it.
1116 # Else favor successors with fewer exits.
1117 # Break ties via max distance from board centerpoint (favor
1118 # corners and edges whenever possible).
1119 candidates = []
1120 for i in succs[self.lastij]:
Tim Peters9a8c8e22001-07-13 09:12:12 +00001121 e = len(succs[i])
1122 assert e > 0, "else remove_from_successors() pruning flawed"
1123 if e == 1:
1124 candidates = [(e, 0, i)]
1125 break
1126 i1, j1 = self.index2coords(i)
1127 d = (i1 - vmid)**2 + (j1 - hmid)**2
1128 candidates.append((e, -d, i))
unknown31569562001-07-04 22:11:22 +00001129 else:
1130 candidates.sort()
1131
1132 for e, d, i in candidates:
1133 if i != self.final:
Tim Peters9a8c8e22001-07-13 09:12:12 +00001134 if remove_from_successors(i):
unknown31569562001-07-04 22:11:22 +00001135 self.lastij = i
1136 yield i
Tim Peters9a8c8e22001-07-13 09:12:12 +00001137 add_to_successors(i)
unknown31569562001-07-04 22:11:22 +00001138
1139 # Generate the last move.
1140 def last():
1141 assert self.final in succs[self.lastij]
1142 yield self.final
1143
Tim Peters9a8c8e22001-07-13 09:12:12 +00001144 if m*n < 4:
1145 self.squaregenerators = [first]
unknown31569562001-07-04 22:11:22 +00001146 else:
Tim Peters9a8c8e22001-07-13 09:12:12 +00001147 self.squaregenerators = [first, second] + \
1148 [hard and advance_hard or advance] * (m*n - 3) + \
unknown31569562001-07-04 22:11:22 +00001149 [last]
1150
Tim Peters9a8c8e22001-07-13 09:12:12 +00001151 def coords2index(self, i, j):
1152 assert 0 <= i < self.m
1153 assert 0 <= j < self.n
1154 return i * self.n + j
1155
1156 def index2coords(self, index):
1157 assert 0 <= index < self.m * self.n
1158 return divmod(index, self.n)
1159
1160 def _init_board(self):
1161 succs = self.succs
1162 del succs[:]
1163 m, n = self.m, self.n
1164 c2i = self.coords2index
1165
1166 offsets = [( 1, 2), ( 2, 1), ( 2, -1), ( 1, -2),
1167 (-1, -2), (-2, -1), (-2, 1), (-1, 2)]
1168 rangen = range(n)
1169 for i in range(m):
1170 for j in rangen:
1171 s = [c2i(i+io, j+jo) for io, jo in offsets
1172 if 0 <= i+io < m and
1173 0 <= j+jo < n]
1174 succs.append(s)
1175
unknown31569562001-07-04 22:11:22 +00001176 # Generate solutions.
1177 def solve(self):
Tim Peters9a8c8e22001-07-13 09:12:12 +00001178 self._init_board()
1179 for x in conjoin(self.squaregenerators):
unknown31569562001-07-04 22:11:22 +00001180 yield x
1181
1182 def printsolution(self, x):
Tim Peters9a8c8e22001-07-13 09:12:12 +00001183 m, n = self.m, self.n
1184 assert len(x) == m*n
1185 w = len(str(m*n))
unknown31569562001-07-04 22:11:22 +00001186 format = "%" + str(w) + "d"
1187
Tim Peters9a8c8e22001-07-13 09:12:12 +00001188 squares = [[None] * n for i in range(m)]
unknown31569562001-07-04 22:11:22 +00001189 k = 1
1190 for i in x:
Tim Peters9a8c8e22001-07-13 09:12:12 +00001191 i1, j1 = self.index2coords(i)
unknown31569562001-07-04 22:11:22 +00001192 squares[i1][j1] = format % k
1193 k += 1
1194
1195 sep = "+" + ("-" * w + "+") * n
1196 print sep
Tim Peters9a8c8e22001-07-13 09:12:12 +00001197 for i in range(m):
unknown31569562001-07-04 22:11:22 +00001198 row = squares[i]
1199 print "|" + "|".join(row) + "|"
1200 print sep
1201
Tim Petersbe4f0a72001-06-29 02:41:16 +00001202conjoin_tests = """
1203
1204Generate the 3-bit binary numbers in order. This illustrates dumbest-
1205possible use of conjoin, just to generate the full cross-product.
1206
unknown31569562001-07-04 22:11:22 +00001207>>> for c in conjoin([lambda: iter((0, 1))] * 3):
Tim Petersbe4f0a72001-06-29 02:41:16 +00001208... print c
1209[0, 0, 0]
1210[0, 0, 1]
1211[0, 1, 0]
1212[0, 1, 1]
1213[1, 0, 0]
1214[1, 0, 1]
1215[1, 1, 0]
1216[1, 1, 1]
1217
Tim Petersc468fd22001-06-30 07:29:44 +00001218For efficiency in typical backtracking apps, conjoin() yields the same list
1219object each time. So if you want to save away a full account of its
1220generated sequence, you need to copy its results.
1221
1222>>> def gencopy(iterator):
1223... for x in iterator:
1224... yield x[:]
1225
1226>>> for n in range(10):
unknown31569562001-07-04 22:11:22 +00001227... all = list(gencopy(conjoin([lambda: iter((0, 1))] * n)))
Tim Petersc468fd22001-06-30 07:29:44 +00001228... print n, len(all), all[0] == [0] * n, all[-1] == [1] * n
12290 1 1 1
12301 2 1 1
12312 4 1 1
12323 8 1 1
12334 16 1 1
12345 32 1 1
12356 64 1 1
12367 128 1 1
12378 256 1 1
12389 512 1 1
1239
Tim Petersbe4f0a72001-06-29 02:41:16 +00001240And run an 8-queens solver.
1241
1242>>> q = Queens(8)
1243>>> LIMIT = 2
1244>>> count = 0
1245>>> for row2col in q.solve():
1246... count += 1
1247... if count <= LIMIT:
1248... print "Solution", count
1249... q.printsolution(row2col)
1250Solution 1
1251+-+-+-+-+-+-+-+-+
1252|Q| | | | | | | |
1253+-+-+-+-+-+-+-+-+
1254| | | | |Q| | | |
1255+-+-+-+-+-+-+-+-+
1256| | | | | | | |Q|
1257+-+-+-+-+-+-+-+-+
1258| | | | | |Q| | |
1259+-+-+-+-+-+-+-+-+
1260| | |Q| | | | | |
1261+-+-+-+-+-+-+-+-+
1262| | | | | | |Q| |
1263+-+-+-+-+-+-+-+-+
1264| |Q| | | | | | |
1265+-+-+-+-+-+-+-+-+
1266| | | |Q| | | | |
1267+-+-+-+-+-+-+-+-+
1268Solution 2
1269+-+-+-+-+-+-+-+-+
1270|Q| | | | | | | |
1271+-+-+-+-+-+-+-+-+
1272| | | | | |Q| | |
1273+-+-+-+-+-+-+-+-+
1274| | | | | | | |Q|
1275+-+-+-+-+-+-+-+-+
1276| | |Q| | | | | |
1277+-+-+-+-+-+-+-+-+
1278| | | | | | |Q| |
1279+-+-+-+-+-+-+-+-+
1280| | | |Q| | | | |
1281+-+-+-+-+-+-+-+-+
1282| |Q| | | | | | |
1283+-+-+-+-+-+-+-+-+
1284| | | | |Q| | | |
1285+-+-+-+-+-+-+-+-+
1286
1287>>> print count, "solutions in all."
128892 solutions in all.
unknown31569562001-07-04 22:11:22 +00001289
1290And run a Knight's Tour on a 10x10 board. Note that there are about
129120,000 solutions even on a 6x6 board, so don't dare run this to exhaustion.
1292
Tim Peters9a8c8e22001-07-13 09:12:12 +00001293>>> k = Knights(10, 10)
unknown31569562001-07-04 22:11:22 +00001294>>> LIMIT = 2
1295>>> count = 0
1296>>> for x in k.solve():
1297... count += 1
1298... if count <= LIMIT:
1299... print "Solution", count
1300... k.printsolution(x)
1301... else:
1302... break
1303Solution 1
1304+---+---+---+---+---+---+---+---+---+---+
1305| 1| 58| 27| 34| 3| 40| 29| 10| 5| 8|
1306+---+---+---+---+---+---+---+---+---+---+
1307| 26| 35| 2| 57| 28| 33| 4| 7| 30| 11|
1308+---+---+---+---+---+---+---+---+---+---+
1309| 59|100| 73| 36| 41| 56| 39| 32| 9| 6|
1310+---+---+---+---+---+---+---+---+---+---+
1311| 74| 25| 60| 55| 72| 37| 42| 49| 12| 31|
1312+---+---+---+---+---+---+---+---+---+---+
1313| 61| 86| 99| 76| 63| 52| 47| 38| 43| 50|
1314+---+---+---+---+---+---+---+---+---+---+
1315| 24| 75| 62| 85| 54| 71| 64| 51| 48| 13|
1316+---+---+---+---+---+---+---+---+---+---+
1317| 87| 98| 91| 80| 77| 84| 53| 46| 65| 44|
1318+---+---+---+---+---+---+---+---+---+---+
1319| 90| 23| 88| 95| 70| 79| 68| 83| 14| 17|
1320+---+---+---+---+---+---+---+---+---+---+
1321| 97| 92| 21| 78| 81| 94| 19| 16| 45| 66|
1322+---+---+---+---+---+---+---+---+---+---+
1323| 22| 89| 96| 93| 20| 69| 82| 67| 18| 15|
1324+---+---+---+---+---+---+---+---+---+---+
1325Solution 2
1326+---+---+---+---+---+---+---+---+---+---+
1327| 1| 58| 27| 34| 3| 40| 29| 10| 5| 8|
1328+---+---+---+---+---+---+---+---+---+---+
1329| 26| 35| 2| 57| 28| 33| 4| 7| 30| 11|
1330+---+---+---+---+---+---+---+---+---+---+
1331| 59|100| 73| 36| 41| 56| 39| 32| 9| 6|
1332+---+---+---+---+---+---+---+---+---+---+
1333| 74| 25| 60| 55| 72| 37| 42| 49| 12| 31|
1334+---+---+---+---+---+---+---+---+---+---+
1335| 61| 86| 99| 76| 63| 52| 47| 38| 43| 50|
1336+---+---+---+---+---+---+---+---+---+---+
1337| 24| 75| 62| 85| 54| 71| 64| 51| 48| 13|
1338+---+---+---+---+---+---+---+---+---+---+
1339| 87| 98| 89| 80| 77| 84| 53| 46| 65| 44|
1340+---+---+---+---+---+---+---+---+---+---+
1341| 90| 23| 92| 95| 70| 79| 68| 83| 14| 17|
1342+---+---+---+---+---+---+---+---+---+---+
1343| 97| 88| 21| 78| 81| 94| 19| 16| 45| 66|
1344+---+---+---+---+---+---+---+---+---+---+
1345| 22| 91| 96| 93| 20| 69| 82| 67| 18| 15|
1346+---+---+---+---+---+---+---+---+---+---+
Tim Petersbe4f0a72001-06-29 02:41:16 +00001347"""
1348
Tim Petersf6ed0742001-06-27 07:17:57 +00001349__test__ = {"tut": tutorial_tests,
1350 "pep": pep_tests,
1351 "email": email_tests,
1352 "fun": fun_tests,
Tim Petersbe4f0a72001-06-29 02:41:16 +00001353 "syntax": syntax_tests,
1354 "conjoin": conjoin_tests}
Tim Peters1def3512001-06-23 20:27:04 +00001355
1356# Magic test name that regrtest.py invokes *after* importing this module.
1357# This worms around a bootstrap problem.
1358# Note that doctest and regrtest both look in sys.argv for a "-v" argument,
1359# so this works as expected in both ways of running regrtest.
1360def test_main():
1361 import doctest, test_generators
Tim Petersa1d54552001-07-12 22:55:42 +00001362 if 0: # change to 1 to run forever (to check for leaks)
1363 while 1:
Tim Peters2106ef02001-06-25 01:30:12 +00001364 doctest.master = None
1365 doctest.testmod(test_generators)
Tim Petersa1d54552001-07-12 22:55:42 +00001366 print ".",
Tim Peters2106ef02001-06-25 01:30:12 +00001367 else:
1368 doctest.testmod(test_generators)
Tim Peters1def3512001-06-23 20:27:04 +00001369
1370# This part isn't needed for regrtest, but for running the test directly.
1371if __name__ == "__main__":
1372 test_main()