Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit b2bc6a9

Browse files
committed
Added a "generate k-combinations of a list" example posted to c.l.py.
1 parent ea2e97a commit b2bc6a9

1 file changed

Lines changed: 49 additions & 1 deletion

File tree

Lib/test/test_generators.py

Lines changed: 49 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -281,7 +281,7 @@
281281
282282
"""
283283

284-
# A few examples from Iterator-List and Python-Dev email.
284+
# Examples from Iterator-List and Python-Dev and c.l.py.
285285

286286
email_tests = """
287287
@@ -319,6 +319,54 @@
319319
...
320320
File "<string>", line 2, in g
321321
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]:
322370
"""
323371

324372
# Fun tests (for sufficiently warped notions of "fun").

0 commit comments

Comments
 (0)