|
281 | 281 |
|
282 | 282 | """ |
283 | 283 |
|
284 | | -# A few examples from Iterator-List and Python-Dev email. |
| 284 | +# Examples from Iterator-List and Python-Dev and c.l.py. |
285 | 285 |
|
286 | 286 | email_tests = """ |
287 | 287 |
|
|
319 | 319 | ... |
320 | 320 | File "<string>", line 2, in g |
321 | 321 | ValueError: generator already executing |
| 322 | +
|
| 323 | +Next one was posted to c.l.py. |
| 324 | +
|
| 325 | +>>> def gcomb(x, k): |
| 326 | +... "Generate all combinations of k elements from list x." |
| 327 | +... |
| 328 | +... if k > len(x): |
| 329 | +... return |
| 330 | +... if k == 0: |
| 331 | +... yield [] |
| 332 | +... else: |
| 333 | +... first, rest = x[0], x[1:] |
| 334 | +... # A combination does or doesn't contain first. |
| 335 | +... # If it does, the remainder is a k-1 comb of rest. |
| 336 | +... for c in gcomb(rest, k-1): |
| 337 | +... c.insert(0, first) |
| 338 | +... yield c |
| 339 | +... # If it doesn't contain first, it's a k comb of rest. |
| 340 | +... for c in gcomb(rest, k): |
| 341 | +... yield c |
| 342 | +
|
| 343 | +>>> seq = range(1, 5) |
| 344 | +>>> for k in range(len(seq) + 2): |
| 345 | +... print "%d-combs of %s:" % (k, seq) |
| 346 | +... for c in gcomb(seq, k): |
| 347 | +... print " ", c |
| 348 | +0-combs of [1, 2, 3, 4]: |
| 349 | + [] |
| 350 | +1-combs of [1, 2, 3, 4]: |
| 351 | + [1] |
| 352 | + [2] |
| 353 | + [3] |
| 354 | + [4] |
| 355 | +2-combs of [1, 2, 3, 4]: |
| 356 | + [1, 2] |
| 357 | + [1, 3] |
| 358 | + [1, 4] |
| 359 | + [2, 3] |
| 360 | + [2, 4] |
| 361 | + [3, 4] |
| 362 | +3-combs of [1, 2, 3, 4]: |
| 363 | + [1, 2, 3] |
| 364 | + [1, 2, 4] |
| 365 | + [1, 3, 4] |
| 366 | + [2, 3, 4] |
| 367 | +4-combs of [1, 2, 3, 4]: |
| 368 | + [1, 2, 3, 4] |
| 369 | +5-combs of [1, 2, 3, 4]: |
322 | 370 | """ |
323 | 371 |
|
324 | 372 | # Fun tests (for sufficiently warped notions of "fun"). |
|
0 commit comments