Tim Peters | 6ba5f79 | 2001-06-23 20:45:43 +0000 | [diff] [blame] | 1 | tutorial_tests = """ |
Tim Peters | 1def351 | 2001-06-23 20:27:04 +0000 | [diff] [blame] | 2 | Let's try a simple generator: |
| 3 | |
| 4 | >>> def f(): |
| 5 | ... yield 1 |
| 6 | ... yield 2 |
| 7 | |
Tim Peters | b9e9ff1 | 2001-06-24 03:44:52 +0000 | [diff] [blame] | 8 | >>> for i in f(): |
| 9 | ... print i |
| 10 | 1 |
| 11 | 2 |
Tim Peters | 1def351 | 2001-06-23 20:27:04 +0000 | [diff] [blame] | 12 | >>> g = f() |
| 13 | >>> g.next() |
| 14 | 1 |
| 15 | >>> g.next() |
| 16 | 2 |
Tim Peters | ea2e97a | 2001-06-24 07:10:02 +0000 | [diff] [blame] | 17 | |
Tim Peters | 2106ef0 | 2001-06-25 01:30:12 +0000 | [diff] [blame] | 18 | "Falling off the end" stops the generator: |
Tim Peters | ea2e97a | 2001-06-24 07:10:02 +0000 | [diff] [blame] | 19 | |
Tim Peters | 1def351 | 2001-06-23 20:27:04 +0000 | [diff] [blame] | 20 | >>> 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 Peters | ea2e97a | 2001-06-24 07:10:02 +0000 | [diff] [blame] | 26 | "return" also stops the generator: |
Tim Peters | 1def351 | 2001-06-23 20:27:04 +0000 | [diff] [blame] | 27 | |
| 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 Peters | 3446365 | 2001-07-12 22:43:41 +0000 | [diff] [blame] | 50 | ... raise StopIteration |
Tim Peters | 1def351 | 2001-06-23 20:27:04 +0000 | [diff] [blame] | 51 | ... 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 | |
| 65 | However, 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 | |
| 84 | This 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 | |
| 95 | Let'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 | |
| 104 | Generators 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 | |
| 123 | Generators 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 Peters | 6ba5f79 | 2001-06-23 20:45:43 +0000 | [diff] [blame] | 134 | # The examples from PEP 255. |
| 135 | |
| 136 | pep_tests = """ |
| 137 | |
Tim Peters | e561463 | 2001-08-15 04:41:19 +0000 | [diff] [blame] | 138 | Specification: 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 Peters | 6ba5f79 | 2001-06-23 20:45:43 +0000 | [diff] [blame] | 153 | Specification: 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 | |
| 180 | Specification: Generators and Exception Propagation |
| 181 | |
| 182 | >>> def f(): |
Tim Peters | 3caca23 | 2001-12-06 06:23:26 +0000 | [diff] [blame] | 183 | ... return 1//0 |
Tim Peters | 6ba5f79 | 2001-06-23 20:45:43 +0000 | [diff] [blame] | 184 | >>> 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 | |
| 200 | Specification: Try/Except/Finally |
| 201 | |
| 202 | >>> def f(): |
| 203 | ... try: |
| 204 | ... yield 1 |
| 205 | ... try: |
| 206 | ... yield 2 |
Tim Peters | 3caca23 | 2001-12-06 06:23:26 +0000 | [diff] [blame] | 207 | ... 1//0 |
Tim Peters | 6ba5f79 | 2001-06-23 20:45:43 +0000 | [diff] [blame] | 208 | ... 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 Peters | 6ba5f79 | 2001-06-23 20:45:43 +0000 | [diff] [blame] | 228 | Guido'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 Peters | 3caca23 | 2001-12-06 06:23:26 +0000 | [diff] [blame] | 254 | ... i = n // 2 |
Tim Peters | 6ba5f79 | 2001-06-23 20:45:43 +0000 | [diff] [blame] | 255 | ... 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 Peters | d674e17 | 2002-03-10 07:59:13 +0000 | [diff] [blame] | 260 | >>> # A recursive generator that generates Tree labels in in-order. |
Tim Peters | 6ba5f79 | 2001-06-23 20:45:43 +0000 | [diff] [blame] | 261 | >>> 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 Peters | b2bc6a9 | 2001-06-24 10:14:27 +0000 | [diff] [blame] | 299 | # Examples from Iterator-List and Python-Dev and c.l.py. |
Tim Peters | 6ba5f79 | 2001-06-23 20:45:43 +0000 | [diff] [blame] | 300 | |
| 301 | email_tests = """ |
| 302 | |
| 303 | The 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 | |
| 313 | Ensure that explicitly raising StopIteration acts like any other exception |
| 314 | in 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 Peters | b9e9ff1 | 2001-06-24 03:44:52 +0000 | [diff] [blame] | 325 | |
Tim Peters | b2bc6a9 | 2001-06-24 10:14:27 +0000 | [diff] [blame] | 326 | Next 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 |
| 351 | 0-combs of [1, 2, 3, 4]: |
| 352 | [] |
| 353 | 1-combs of [1, 2, 3, 4]: |
| 354 | [1] |
| 355 | [2] |
| 356 | [3] |
| 357 | [4] |
| 358 | 2-combs of [1, 2, 3, 4]: |
| 359 | [1, 2] |
| 360 | [1, 3] |
| 361 | [1, 4] |
| 362 | [2, 3] |
| 363 | [2, 4] |
| 364 | [3, 4] |
| 365 | 3-combs of [1, 2, 3, 4]: |
| 366 | [1, 2, 3] |
| 367 | [1, 2, 4] |
| 368 | [1, 3, 4] |
| 369 | [2, 3, 4] |
| 370 | 4-combs of [1, 2, 3, 4]: |
| 371 | [1, 2, 3, 4] |
| 372 | 5-combs of [1, 2, 3, 4]: |
Tim Peters | 3e7b1a0 | 2001-06-25 19:46:25 +0000 | [diff] [blame] | 373 | |
Tim Peters | e77f2e2 | 2001-06-26 22:24:51 +0000 | [diff] [blame] | 374 | From the Iterators list, about the types of these things. |
Tim Peters | 3e7b1a0 | 2001-06-25 19:46:25 +0000 | [diff] [blame] | 375 | |
| 376 | >>> def g(): |
| 377 | ... yield 1 |
| 378 | ... |
| 379 | >>> type(g) |
| 380 | <type 'function'> |
| 381 | >>> i = g() |
| 382 | >>> type(i) |
| 383 | <type 'generator'> |
Tim Peters | 5d2b77c | 2001-09-03 05:47:38 +0000 | [diff] [blame] | 384 | >>> [s for s in dir(i) if not s.startswith('_')] |
Tim Peters | e77f2e2 | 2001-06-26 22:24:51 +0000 | [diff] [blame] | 385 | ['gi_frame', 'gi_running', 'next'] |
Tim Peters | 3e7b1a0 | 2001-06-25 19:46:25 +0000 | [diff] [blame] | 386 | >>> print i.next.__doc__ |
Tim Peters | 6d6c1a3 | 2001-08-02 04:15:00 +0000 | [diff] [blame] | 387 | x.next() -> the next value, or raise StopIteration |
Tim Peters | 3e7b1a0 | 2001-06-25 19:46:25 +0000 | [diff] [blame] | 388 | >>> iter(i) is i |
Guido van Rossum | 77f6a65 | 2002-04-03 22:41:51 +0000 | [diff] [blame] | 389 | True |
Tim Peters | 3e7b1a0 | 2001-06-25 19:46:25 +0000 | [diff] [blame] | 390 | >>> import types |
| 391 | >>> isinstance(i, types.GeneratorType) |
Guido van Rossum | 77f6a65 | 2002-04-03 22:41:51 +0000 | [diff] [blame] | 392 | True |
Tim Peters | e77f2e2 | 2001-06-26 22:24:51 +0000 | [diff] [blame] | 393 | |
| 394 | And more, added later. |
| 395 | |
| 396 | >>> i.gi_running |
| 397 | 0 |
| 398 | >>> type(i.gi_frame) |
| 399 | <type 'frame'> |
| 400 | >>> i.gi_running = 42 |
| 401 | Traceback (most recent call last): |
| 402 | ... |
Guido van Rossum | 61cf780 | 2001-08-10 21:25:24 +0000 | [diff] [blame] | 403 | TypeError: readonly attribute |
Tim Peters | e77f2e2 | 2001-06-26 22:24:51 +0000 | [diff] [blame] | 404 | >>> def g(): |
| 405 | ... yield me.gi_running |
| 406 | >>> me = g() |
| 407 | >>> me.gi_running |
| 408 | 0 |
| 409 | >>> me.next() |
| 410 | 1 |
| 411 | >>> me.gi_running |
| 412 | 0 |
Tim Peters | 3530266 | 2001-07-02 01:38:33 +0000 | [diff] [blame] | 413 | |
| 414 | A clever union-find implementation from c.l.py, due to David Eppstein. |
| 415 | Sent: Friday, June 29, 2001 12:16 PM |
| 416 | To: python-list@python.org |
| 417 | Subject: 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 Peters | 3530266 | 2001-07-02 01:38:33 +0000 | [diff] [blame] | 441 | |
| 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 |
| 460 | A->A B->B C->C D->D E->E F->F G->G H->H I->I J->J K->K L->L M->M |
| 461 | merged D into G |
| 462 | A->A B->B C->C D->G E->E F->F G->G H->H I->I J->J K->K L->L M->M |
| 463 | merged C into F |
| 464 | A->A B->B C->F D->G E->E F->F G->G H->H I->I J->J K->K L->L M->M |
| 465 | merged L into A |
| 466 | A->A B->B C->F D->G E->E F->F G->G H->H I->I J->J K->K L->A M->M |
| 467 | merged H into E |
| 468 | A->A B->B C->F D->G E->E F->F G->G H->E I->I J->J K->K L->A M->M |
| 469 | merged B into E |
| 470 | A->A B->E C->F D->G E->E F->F G->G H->E I->I J->J K->K L->A M->M |
| 471 | merged J into G |
| 472 | A->A B->E C->F D->G E->E F->F G->G H->E I->I J->G K->K L->A M->M |
| 473 | merged E into G |
| 474 | A->A B->G C->F D->G E->G F->F G->G H->G I->I J->G K->K L->A M->M |
| 475 | merged M into G |
| 476 | A->A B->G C->F D->G E->G F->F G->G H->G I->I J->G K->K L->A M->G |
| 477 | merged I into K |
| 478 | A->A B->G C->F D->G E->G F->F G->G H->G I->K J->G K->K L->A M->G |
| 479 | merged K into A |
| 480 | A->A B->G C->F D->G E->G F->F G->G H->G I->A J->G K->A L->A M->G |
| 481 | merged F into A |
| 482 | A->A B->G C->A D->G E->G F->A G->G H->G I->A J->G K->A L->A M->G |
| 483 | merged A into G |
| 484 | A->G B->G C->G D->G E->G F->G G->G H->G I->G J->G K->G L->G M->G |
Tim Peters | 6ba5f79 | 2001-06-23 20:45:43 +0000 | [diff] [blame] | 485 | """ |
| 486 | |
Tim Peters | 0f9da0a | 2001-06-23 21:01:47 +0000 | [diff] [blame] | 487 | # Fun tests (for sufficiently warped notions of "fun"). |
| 488 | |
| 489 | fun_tests = """ |
| 490 | |
| 491 | Build 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 Peters | b9e9ff1 | 2001-06-24 03:44:52 +0000 | [diff] [blame] | 522 | |
Tim Peters | f6ed074 | 2001-06-27 07:17:57 +0000 | [diff] [blame] | 523 | |
Tim Peters | b9e9ff1 | 2001-06-24 03:44:52 +0000 | [diff] [blame] | 524 | Another famous problem: generate all integers of the form |
| 525 | 2**i * 3**j * 5**k |
| 526 | in increasing order, where i,j,k >= 0. Trickier than it may look at first! |
| 527 | Try writing it without generators, and correctly, and without generating |
| 528 | 3 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 Peters | f6ed074 | 2001-06-27 07:17:57 +0000 | [diff] [blame] | 551 | The following works, but is doing a whale of a lot of redundant work -- |
| 552 | it's not clear how to get the internal uses of m235 to share a single |
| 553 | generator. Note that me_times2 (etc) each need to see every element in the |
| 554 | result 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 Peters | b9e9ff1 | 2001-06-24 03:44:52 +0000 | [diff] [blame] | 556 | |
| 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 Peters | f6ed074 | 2001-06-27 07:17:57 +0000 | [diff] [blame] | 567 | Don't print "too many" of these -- the implementation above is extremely |
| 568 | inefficient: each call of m235() leads to 3 recursive calls, and in |
| 569 | turn each of those 3 more, and so on, and so on, until we've descended |
| 570 | enough levels to satisfy the print stmts. Very odd: when I printed 5 |
| 571 | lines of results below, this managed to screw up Win98's malloc in "the |
| 572 | usual" way, i.e. the heap grew over 4Mb so Win98 started fragmenting |
| 573 | address space, and it *looked* like a very slow leak. |
| 574 | |
Tim Peters | b9e9ff1 | 2001-06-24 03:44:52 +0000 | [diff] [blame] | 575 | >>> result = m235() |
Tim Peters | f6ed074 | 2001-06-27 07:17:57 +0000 | [diff] [blame] | 576 | >>> for i in range(3): |
Tim Peters | b9e9ff1 | 2001-06-24 03:44:52 +0000 | [diff] [blame] | 577 | ... 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 Peters | ee30927 | 2001-06-24 05:47:06 +0000 | [diff] [blame] | 581 | |
| 582 | Heh. Here's one way to get a shared list, complete with an excruciating |
| 583 | namespace renaming trick. The *pretty* part is that the times() and merge() |
| 584 | functions can be reused as-is, because they only assume their stream |
| 585 | arguments 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 Peters | ea2e97a | 2001-06-24 07:10:02 +0000 | [diff] [blame] | 600 | ... # Gack: m235 below actually refers to a LazyList. |
Tim Peters | ee30927 | 2001-06-24 05:47:06 +0000 | [diff] [blame] | 601 | ... 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 Peters | f6ed074 | 2001-06-27 07:17:57 +0000 | [diff] [blame] | 609 | Print as many of these as you like -- *this* implementation is memory- |
Neil Schemenauer | b20e9db | 2001-07-12 13:26:41 +0000 | [diff] [blame] | 610 | efficient. |
Tim Peters | f6ed074 | 2001-06-27 07:17:57 +0000 | [diff] [blame] | 611 | |
Tim Peters | ee30927 | 2001-06-24 05:47:06 +0000 | [diff] [blame] | 612 | >>> 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 Peters | f6ed074 | 2001-06-27 07:17:57 +0000 | [diff] [blame] | 620 | |
Tim Peters | f6ed074 | 2001-06-27 07:17:57 +0000 | [diff] [blame] | 621 | |
| 622 | Ye 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 Peters | 0f9da0a | 2001-06-23 21:01:47 +0000 | [diff] [blame] | 644 | """ |
| 645 | |
Tim Peters | b6c3cea | 2001-06-26 03:36:28 +0000 | [diff] [blame] | 646 | # syntax_tests mostly provokes SyntaxErrors. Also fiddling with #if 0 |
| 647 | # hackery. |
Tim Peters | ee30927 | 2001-06-24 05:47:06 +0000 | [diff] [blame] | 648 | |
Tim Peters | ea2e97a | 2001-06-24 07:10:02 +0000 | [diff] [blame] | 649 | syntax_tests = """ |
| 650 | |
| 651 | >>> def f(): |
| 652 | ... return 22 |
| 653 | ... yield 1 |
| 654 | Traceback (most recent call last): |
| 655 | ... |
| 656 | SyntaxError: 'return' with argument inside generator (<string>, line 2) |
| 657 | |
| 658 | >>> def f(): |
| 659 | ... yield 1 |
| 660 | ... return 22 |
| 661 | Traceback (most recent call last): |
| 662 | ... |
| 663 | SyntaxError: '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 |
| 670 | Traceback (most recent call last): |
| 671 | ... |
| 672 | SyntaxError: 'return' with argument inside generator (<string>, line 3) |
| 673 | |
| 674 | This 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 |
| 685 | Traceback (most recent call last): |
| 686 | ... |
| 687 | SyntaxError: 'yield' not allowed in a 'try' block with a 'finally' clause (<string>, line 3) |
| 688 | |
| 689 | >>> def f(): |
| 690 | ... try: |
| 691 | ... try: |
Tim Peters | 3caca23 | 2001-12-06 06:23:26 +0000 | [diff] [blame] | 692 | ... 1//0 |
Tim Peters | ea2e97a | 2001-06-24 07:10:02 +0000 | [diff] [blame] | 693 | ... except ZeroDivisionError: |
| 694 | ... yield 666 # bad because *outer* try has finally |
| 695 | ... except: |
| 696 | ... pass |
| 697 | ... finally: |
| 698 | ... pass |
| 699 | Traceback (most recent call last): |
| 700 | ... |
| 701 | SyntaxError: 'yield' not allowed in a 'try' block with a 'finally' clause (<string>, line 6) |
| 702 | |
| 703 | But this is fine: |
| 704 | |
| 705 | >>> def f(): |
| 706 | ... try: |
| 707 | ... try: |
| 708 | ... yield 12 |
Tim Peters | 3caca23 | 2001-12-06 06:23:26 +0000 | [diff] [blame] | 709 | ... 1//0 |
Tim Peters | ea2e97a | 2001-06-24 07:10:02 +0000 | [diff] [blame] | 710 | ... 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 Peters | b6c3cea | 2001-06-26 03:36:28 +0000 | [diff] [blame] | 721 | |
| 722 | >>> def f(): |
Tim Peters | 08a898f | 2001-06-28 01:52:22 +0000 | [diff] [blame] | 723 | ... yield |
| 724 | Traceback (most recent call last): |
| 725 | SyntaxError: invalid syntax |
| 726 | |
| 727 | >>> def f(): |
| 728 | ... if 0: |
| 729 | ... yield |
| 730 | Traceback (most recent call last): |
| 731 | SyntaxError: invalid syntax |
| 732 | |
| 733 | >>> def f(): |
Tim Peters | b6c3cea | 2001-06-26 03:36:28 +0000 | [diff] [blame] | 734 | ... 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 Peters | 3caca23 | 2001-12-06 06:23:26 +0000 | [diff] [blame] | 752 | ... 1//0 |
Tim Peters | b6c3cea | 2001-06-26 03:36:28 +0000 | [diff] [blame] | 753 | ... 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 Rossum | 297abad | 2001-08-16 08:32:39 +0000 | [diff] [blame] | 775 | <type 'NoneType'> |
Tim Peters | b6c3cea | 2001-06-26 03:36:28 +0000 | [diff] [blame] | 776 | |
| 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 Rossum | 297abad | 2001-08-16 08:32:39 +0000 | [diff] [blame] | 785 | <type 'NoneType'> |
Tim Peters | 08a898f | 2001-06-28 01:52:22 +0000 | [diff] [blame] | 786 | |
| 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 |
| 806 | Traceback (most recent call last): |
| 807 | SyntaxError: 'return' with argument inside generator (<string>, line 8) |
Guido van Rossum | c5fe5eb | 2002-06-12 03:45:21 +0000 | [diff] [blame] | 808 | |
| 809 | This 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 |
Tim Peters | c411dba | 2002-07-16 21:35:23 +0000 | [diff] [blame] | 817 | ... |
Guido van Rossum | c5fe5eb | 2002-06-12 03:45:21 +0000 | [diff] [blame] | 818 | >>> g = f() |
| 819 | >>> print g.next() |
| 820 | 0 |
| 821 | >>> print g.next() |
| 822 | 1 |
| 823 | >>> print g.next() |
| 824 | 2 |
| 825 | >>> print g.next() |
| 826 | Traceback (most recent call last): |
| 827 | StopIteration |
Tim Peters | ea2e97a | 2001-06-24 07:10:02 +0000 | [diff] [blame] | 828 | """ |
| 829 | |
Tim Peters | be4f0a7 | 2001-06-29 02:41:16 +0000 | [diff] [blame] | 830 | # 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 | |
| 850 | def 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 Peters | c468fd2 | 2001-06-30 07:29:44 +0000 | [diff] [blame] | 865 | # 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 | |
| 871 | def 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 | |
unknown | 3156956 | 2001-07-04 22:11:22 +0000 | [diff] [blame] | 921 | # 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 Peters | 9a8c8e2 | 2001-07-13 09:12:12 +0000 | [diff] [blame] | 929 | # much harder to achieve. OTOH, this is much slower (up to a factor of 2) |
| 930 | # than the fancy unrolled recursive conjoin. |
unknown | 3156956 | 2001-07-04 22:11:22 +0000 | [diff] [blame] | 931 | |
| 932 | def 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 Peters | 9a8c8e2 | 2001-07-13 09:12:12 +0000 | [diff] [blame] | 936 | _StopIteration = StopIteration # make local because caught a *lot* |
unknown | 3156956 | 2001-07-04 22:11:22 +0000 | [diff] [blame] | 937 | i = 0 |
Tim Peters | 9a8c8e2 | 2001-07-13 09:12:12 +0000 | [diff] [blame] | 938 | 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 |
unknown | 3156956 | 2001-07-04 22:11:22 +0000 | [diff] [blame] | 947 | else: |
Tim Peters | 9a8c8e2 | 2001-07-13 09:12:12 +0000 | [diff] [blame] | 948 | assert i == n |
| 949 | yield values |
unknown | 3156956 | 2001-07-04 22:11:22 +0000 | [diff] [blame] | 950 | |
Tim Peters | 9a8c8e2 | 2001-07-13 09:12:12 +0000 | [diff] [blame] | 951 | # Backtrack until an older iterator can be resumed. |
| 952 | i -= 1 |
unknown | 3156956 | 2001-07-04 22:11:22 +0000 | [diff] [blame] | 953 | while i >= 0: |
| 954 | try: |
| 955 | values[i] = iters[i]() |
Tim Peters | 9a8c8e2 | 2001-07-13 09:12:12 +0000 | [diff] [blame] | 956 | # Success! Start fresh at next level. |
unknown | 3156956 | 2001-07-04 22:11:22 +0000 | [diff] [blame] | 957 | i += 1 |
| 958 | break |
Tim Peters | 9a8c8e2 | 2001-07-13 09:12:12 +0000 | [diff] [blame] | 959 | except _StopIteration: |
| 960 | # Continue backtracking. |
| 961 | i -= 1 |
| 962 | else: |
| 963 | assert i < 0 |
| 964 | break |
unknown | 3156956 | 2001-07-04 22:11:22 +0000 | [diff] [blame] | 965 | |
Tim Peters | be4f0a7 | 2001-06-29 02:41:16 +0000 | [diff] [blame] | 966 | # A conjoin-based N-Queens solver. |
| 967 | |
| 968 | class 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 Peters | c468fd2 | 2001-06-30 07:29:44 +0000 | [diff] [blame] | 994 | if uses & self.used == 0: |
| 995 | self.used |= uses |
| 996 | yield j |
| 997 | self.used &= ~uses |
Tim Peters | be4f0a7 | 2001-06-29 02:41:16 +0000 | [diff] [blame] | 998 | |
| 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 | |
unknown | 3156956 | 2001-07-04 22:11:22 +0000 | [diff] [blame] | 1018 | # 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 Peters | 9a8c8e2 | 2001-07-13 09:12:12 +0000 | [diff] [blame] | 1021 | # creating 10s of thousands of generators then!), and is lengthy. |
unknown | 3156956 | 2001-07-04 22:11:22 +0000 | [diff] [blame] | 1022 | |
| 1023 | class Knights: |
Tim Peters | 9a8c8e2 | 2001-07-13 09:12:12 +0000 | [diff] [blame] | 1024 | def __init__(self, m, n, hard=0): |
| 1025 | self.m, self.n = m, n |
unknown | 3156956 | 2001-07-04 22:11:22 +0000 | [diff] [blame] | 1026 | |
Tim Peters | 9a8c8e2 | 2001-07-13 09:12:12 +0000 | [diff] [blame] | 1027 | # solve() will set up succs[i] to be a list of square #i's |
| 1028 | # successors. |
| 1029 | succs = self.succs = [] |
unknown | 3156956 | 2001-07-04 22:11:22 +0000 | [diff] [blame] | 1030 | |
Tim Peters | 9a8c8e2 | 2001-07-13 09:12:12 +0000 | [diff] [blame] | 1031 | # 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. |
unknown | 3156956 | 2001-07-04 22:11:22 +0000 | [diff] [blame] | 1034 | |
Tim Peters | 9a8c8e2 | 2001-07-13 09:12:12 +0000 | [diff] [blame] | 1035 | def remove_from_successors(i0, len=len): |
unknown | 3156956 | 2001-07-04 22:11:22 +0000 | [diff] [blame] | 1036 | # 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 Peters | 9a8c8e2 | 2001-07-13 09:12:12 +0000 | [diff] [blame] | 1046 | 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 |
unknown | 3156956 | 2001-07-04 22:11:22 +0000 | [diff] [blame] | 1053 | return ne0 == 0 and ne1 < 2 |
| 1054 | |
Tim Peters | 9a8c8e2 | 2001-07-13 09:12:12 +0000 | [diff] [blame] | 1055 | # Put i0 back in each of its successor's successor lists. |
| 1056 | |
| 1057 | def add_to_successors(i0): |
unknown | 3156956 | 2001-07-04 22:11:22 +0000 | [diff] [blame] | 1058 | for i in succs[i0]: |
Tim Peters | 9a8c8e2 | 2001-07-13 09:12:12 +0000 | [diff] [blame] | 1059 | succs[i].append(i0) |
unknown | 3156956 | 2001-07-04 22:11:22 +0000 | [diff] [blame] | 1060 | |
| 1061 | # Generate the first move. |
| 1062 | def first(): |
Tim Peters | 9a8c8e2 | 2001-07-13 09:12:12 +0000 | [diff] [blame] | 1063 | if m < 1 or n < 1: |
unknown | 3156956 | 2001-07-04 22:11:22 +0000 | [diff] [blame] | 1064 | return |
| 1065 | |
unknown | 3156956 | 2001-07-04 22:11:22 +0000 | [diff] [blame] | 1066 | # 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 Peters | 9a8c8e2 | 2001-07-13 09:12:12 +0000 | [diff] [blame] | 1068 | corner = self.coords2index(0, 0) |
| 1069 | remove_from_successors(corner) |
unknown | 3156956 | 2001-07-04 22:11:22 +0000 | [diff] [blame] | 1070 | self.lastij = corner |
| 1071 | yield corner |
Tim Peters | 9a8c8e2 | 2001-07-13 09:12:12 +0000 | [diff] [blame] | 1072 | add_to_successors(corner) |
unknown | 3156956 | 2001-07-04 22:11:22 +0000 | [diff] [blame] | 1073 | |
| 1074 | # Generate the second moves. |
| 1075 | def second(): |
Tim Peters | 9a8c8e2 | 2001-07-13 09:12:12 +0000 | [diff] [blame] | 1076 | corner = self.coords2index(0, 0) |
unknown | 3156956 | 2001-07-04 22:11:22 +0000 | [diff] [blame] | 1077 | assert self.lastij == corner # i.e., we started in the corner |
Tim Peters | 9a8c8e2 | 2001-07-13 09:12:12 +0000 | [diff] [blame] | 1078 | if m < 3 or n < 3: |
unknown | 3156956 | 2001-07-04 22:11:22 +0000 | [diff] [blame] | 1079 | return |
Tim Peters | 9a8c8e2 | 2001-07-13 09:12:12 +0000 | [diff] [blame] | 1080 | assert len(succs[corner]) == 2 |
| 1081 | assert self.coords2index(1, 2) in succs[corner] |
| 1082 | assert self.coords2index(2, 1) in succs[corner] |
unknown | 3156956 | 2001-07-04 22:11:22 +0000 | [diff] [blame] | 1083 | # Only two choices. Whichever we pick, the other must be the |
Tim Peters | 9a8c8e2 | 2001-07-13 09:12:12 +0000 | [diff] [blame] | 1084 | # square picked on move m*n, as it's the only way to get back |
unknown | 3156956 | 2001-07-04 22:11:22 +0000 | [diff] [blame] | 1085 | # 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 Peters | 9a8c8e2 | 2001-07-13 09:12:12 +0000 | [diff] [blame] | 1088 | this = self.coords2index(i, j) |
| 1089 | final = self.coords2index(3-i, 3-j) |
unknown | 3156956 | 2001-07-04 22:11:22 +0000 | [diff] [blame] | 1090 | self.final = final |
unknown | 3156956 | 2001-07-04 22:11:22 +0000 | [diff] [blame] | 1091 | |
Tim Peters | 9a8c8e2 | 2001-07-13 09:12:12 +0000 | [diff] [blame] | 1092 | remove_from_successors(this) |
| 1093 | succs[final].append(corner) |
unknown | 3156956 | 2001-07-04 22:11:22 +0000 | [diff] [blame] | 1094 | self.lastij = this |
| 1095 | yield this |
Tim Peters | 9a8c8e2 | 2001-07-13 09:12:12 +0000 | [diff] [blame] | 1096 | succs[final].remove(corner) |
| 1097 | add_to_successors(this) |
unknown | 3156956 | 2001-07-04 22:11:22 +0000 | [diff] [blame] | 1098 | |
Tim Peters | 9a8c8e2 | 2001-07-13 09:12:12 +0000 | [diff] [blame] | 1099 | # Generate moves 3 thru m*n-1. |
| 1100 | def advance(len=len): |
unknown | 3156956 | 2001-07-04 22:11:22 +0000 | [diff] [blame] | 1101 | # 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 Peters | 9a8c8e2 | 2001-07-13 09:12:12 +0000 | [diff] [blame] | 1105 | 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)) |
unknown | 3156956 | 2001-07-04 22:11:22 +0000 | [diff] [blame] | 1111 | else: |
| 1112 | candidates.sort() |
| 1113 | |
| 1114 | for e, i in candidates: |
| 1115 | if i != self.final: |
Tim Peters | 9a8c8e2 | 2001-07-13 09:12:12 +0000 | [diff] [blame] | 1116 | if remove_from_successors(i): |
unknown | 3156956 | 2001-07-04 22:11:22 +0000 | [diff] [blame] | 1117 | self.lastij = i |
| 1118 | yield i |
Tim Peters | 9a8c8e2 | 2001-07-13 09:12:12 +0000 | [diff] [blame] | 1119 | add_to_successors(i) |
unknown | 3156956 | 2001-07-04 22:11:22 +0000 | [diff] [blame] | 1120 | |
Tim Peters | 9a8c8e2 | 2001-07-13 09:12:12 +0000 | [diff] [blame] | 1121 | # Generate moves 3 thru m*n-1. Alternative version using a |
unknown | 3156956 | 2001-07-04 22:11:22 +0000 | [diff] [blame] | 1122 | # stronger (but more expensive) heuristic to order successors. |
Tim Peters | 9a8c8e2 | 2001-07-13 09:12:12 +0000 | [diff] [blame] | 1123 | # 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): |
unknown | 3156956 | 2001-07-04 22:11:22 +0000 | [diff] [blame] | 1127 | # 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 Peters | 9a8c8e2 | 2001-07-13 09:12:12 +0000 | [diff] [blame] | 1133 | 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)) |
unknown | 3156956 | 2001-07-04 22:11:22 +0000 | [diff] [blame] | 1141 | else: |
| 1142 | candidates.sort() |
| 1143 | |
| 1144 | for e, d, i in candidates: |
| 1145 | if i != self.final: |
Tim Peters | 9a8c8e2 | 2001-07-13 09:12:12 +0000 | [diff] [blame] | 1146 | if remove_from_successors(i): |
unknown | 3156956 | 2001-07-04 22:11:22 +0000 | [diff] [blame] | 1147 | self.lastij = i |
| 1148 | yield i |
Tim Peters | 9a8c8e2 | 2001-07-13 09:12:12 +0000 | [diff] [blame] | 1149 | add_to_successors(i) |
unknown | 3156956 | 2001-07-04 22:11:22 +0000 | [diff] [blame] | 1150 | |
| 1151 | # Generate the last move. |
| 1152 | def last(): |
| 1153 | assert self.final in succs[self.lastij] |
| 1154 | yield self.final |
| 1155 | |
Tim Peters | 9a8c8e2 | 2001-07-13 09:12:12 +0000 | [diff] [blame] | 1156 | if m*n < 4: |
| 1157 | self.squaregenerators = [first] |
unknown | 3156956 | 2001-07-04 22:11:22 +0000 | [diff] [blame] | 1158 | else: |
Tim Peters | 9a8c8e2 | 2001-07-13 09:12:12 +0000 | [diff] [blame] | 1159 | self.squaregenerators = [first, second] + \ |
| 1160 | [hard and advance_hard or advance] * (m*n - 3) + \ |
unknown | 3156956 | 2001-07-04 22:11:22 +0000 | [diff] [blame] | 1161 | [last] |
| 1162 | |
Tim Peters | 9a8c8e2 | 2001-07-13 09:12:12 +0000 | [diff] [blame] | 1163 | 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 | |
unknown | 3156956 | 2001-07-04 22:11:22 +0000 | [diff] [blame] | 1188 | # Generate solutions. |
| 1189 | def solve(self): |
Tim Peters | 9a8c8e2 | 2001-07-13 09:12:12 +0000 | [diff] [blame] | 1190 | self._init_board() |
| 1191 | for x in conjoin(self.squaregenerators): |
unknown | 3156956 | 2001-07-04 22:11:22 +0000 | [diff] [blame] | 1192 | yield x |
| 1193 | |
| 1194 | def printsolution(self, x): |
Tim Peters | 9a8c8e2 | 2001-07-13 09:12:12 +0000 | [diff] [blame] | 1195 | m, n = self.m, self.n |
| 1196 | assert len(x) == m*n |
| 1197 | w = len(str(m*n)) |
unknown | 3156956 | 2001-07-04 22:11:22 +0000 | [diff] [blame] | 1198 | format = "%" + str(w) + "d" |
| 1199 | |
Tim Peters | 9a8c8e2 | 2001-07-13 09:12:12 +0000 | [diff] [blame] | 1200 | squares = [[None] * n for i in range(m)] |
unknown | 3156956 | 2001-07-04 22:11:22 +0000 | [diff] [blame] | 1201 | k = 1 |
| 1202 | for i in x: |
Tim Peters | 9a8c8e2 | 2001-07-13 09:12:12 +0000 | [diff] [blame] | 1203 | i1, j1 = self.index2coords(i) |
unknown | 3156956 | 2001-07-04 22:11:22 +0000 | [diff] [blame] | 1204 | squares[i1][j1] = format % k |
| 1205 | k += 1 |
| 1206 | |
| 1207 | sep = "+" + ("-" * w + "+") * n |
| 1208 | print sep |
Tim Peters | 9a8c8e2 | 2001-07-13 09:12:12 +0000 | [diff] [blame] | 1209 | for i in range(m): |
unknown | 3156956 | 2001-07-04 22:11:22 +0000 | [diff] [blame] | 1210 | row = squares[i] |
| 1211 | print "|" + "|".join(row) + "|" |
| 1212 | print sep |
| 1213 | |
Tim Peters | be4f0a7 | 2001-06-29 02:41:16 +0000 | [diff] [blame] | 1214 | conjoin_tests = """ |
| 1215 | |
| 1216 | Generate the 3-bit binary numbers in order. This illustrates dumbest- |
| 1217 | possible use of conjoin, just to generate the full cross-product. |
| 1218 | |
unknown | 3156956 | 2001-07-04 22:11:22 +0000 | [diff] [blame] | 1219 | >>> for c in conjoin([lambda: iter((0, 1))] * 3): |
Tim Peters | be4f0a7 | 2001-06-29 02:41:16 +0000 | [diff] [blame] | 1220 | ... 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 Peters | c468fd2 | 2001-06-30 07:29:44 +0000 | [diff] [blame] | 1230 | For efficiency in typical backtracking apps, conjoin() yields the same list |
| 1231 | object each time. So if you want to save away a full account of its |
| 1232 | generated 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): |
unknown | 3156956 | 2001-07-04 22:11:22 +0000 | [diff] [blame] | 1239 | ... all = list(gencopy(conjoin([lambda: iter((0, 1))] * n))) |
Tim Peters | c468fd2 | 2001-06-30 07:29:44 +0000 | [diff] [blame] | 1240 | ... print n, len(all), all[0] == [0] * n, all[-1] == [1] * n |
Guido van Rossum | 77f6a65 | 2002-04-03 22:41:51 +0000 | [diff] [blame] | 1241 | 0 1 True True |
| 1242 | 1 2 True True |
| 1243 | 2 4 True True |
| 1244 | 3 8 True True |
| 1245 | 4 16 True True |
| 1246 | 5 32 True True |
| 1247 | 6 64 True True |
| 1248 | 7 128 True True |
| 1249 | 8 256 True True |
| 1250 | 9 512 True True |
Tim Peters | c468fd2 | 2001-06-30 07:29:44 +0000 | [diff] [blame] | 1251 | |
Tim Peters | be4f0a7 | 2001-06-29 02:41:16 +0000 | [diff] [blame] | 1252 | And 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) |
| 1262 | Solution 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 | +-+-+-+-+-+-+-+-+ |
| 1280 | Solution 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." |
| 1300 | 92 solutions in all. |
unknown | 3156956 | 2001-07-04 22:11:22 +0000 | [diff] [blame] | 1301 | |
| 1302 | And run a Knight's Tour on a 10x10 board. Note that there are about |
| 1303 | 20,000 solutions even on a 6x6 board, so don't dare run this to exhaustion. |
| 1304 | |
Tim Peters | 9a8c8e2 | 2001-07-13 09:12:12 +0000 | [diff] [blame] | 1305 | >>> k = Knights(10, 10) |
unknown | 3156956 | 2001-07-04 22:11:22 +0000 | [diff] [blame] | 1306 | >>> 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 |
| 1315 | Solution 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 | +---+---+---+---+---+---+---+---+---+---+ |
| 1337 | Solution 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 Peters | be4f0a7 | 2001-06-29 02:41:16 +0000 | [diff] [blame] | 1359 | """ |
| 1360 | |
Tim Peters | f6ed074 | 2001-06-27 07:17:57 +0000 | [diff] [blame] | 1361 | __test__ = {"tut": tutorial_tests, |
| 1362 | "pep": pep_tests, |
| 1363 | "email": email_tests, |
| 1364 | "fun": fun_tests, |
Tim Peters | be4f0a7 | 2001-06-29 02:41:16 +0000 | [diff] [blame] | 1365 | "syntax": syntax_tests, |
| 1366 | "conjoin": conjoin_tests} |
Tim Peters | 1def351 | 2001-06-23 20:27:04 +0000 | [diff] [blame] | 1367 | |
| 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 Peters | a0a6222 | 2001-09-09 06:12:01 +0000 | [diff] [blame] | 1372 | def test_main(verbose=None): |
| 1373 | import doctest, test_support, test_generators |
Tim Peters | a1d5455 | 2001-07-12 22:55:42 +0000 | [diff] [blame] | 1374 | if 0: # change to 1 to run forever (to check for leaks) |
| 1375 | while 1: |
Tim Peters | 2106ef0 | 2001-06-25 01:30:12 +0000 | [diff] [blame] | 1376 | doctest.master = None |
Tim Peters | a0a6222 | 2001-09-09 06:12:01 +0000 | [diff] [blame] | 1377 | test_support.run_doctest(test_generators, verbose) |
Tim Peters | a1d5455 | 2001-07-12 22:55:42 +0000 | [diff] [blame] | 1378 | print ".", |
Tim Peters | 2106ef0 | 2001-06-25 01:30:12 +0000 | [diff] [blame] | 1379 | else: |
Tim Peters | a0a6222 | 2001-09-09 06:12:01 +0000 | [diff] [blame] | 1380 | test_support.run_doctest(test_generators, verbose) |
Tim Peters | 1def351 | 2001-06-23 20:27:04 +0000 | [diff] [blame] | 1381 | |
| 1382 | # This part isn't needed for regrtest, but for running the test directly. |
| 1383 | if __name__ == "__main__": |
Tim Peters | a0a6222 | 2001-09-09 06:12:01 +0000 | [diff] [blame] | 1384 | test_main(1) |