fork download
  1. # Generate combinations (meh).
  2.  
  3. def combinations(sequence, k):
  4. def inner(start, n, res):
  5. if n == k:
  6. yield tuple(res)
  7. else:
  8. for i in range(start, len(sequence)):
  9. res[n] = sequence[i]
  10. yield from inner(i+1, n+1, res)
  11. return inner(0, 0, [None] * k)
  12.  
  13. # Show.
  14.  
  15. n = 5
  16. a = list(range(1, 1+n))
  17. for k in range(1, 1+n):
  18. print(f'{n} choose {k}')
  19. for x in combinations(a, k):
  20. print('', x)
Success #stdin #stdout 0.11s 14120KB
stdin
Standard input is empty
stdout
5 choose 1
 (1,)
 (2,)
 (3,)
 (4,)
 (5,)
5 choose 2
 (1, 2)
 (1, 3)
 (1, 4)
 (1, 5)
 (2, 3)
 (2, 4)
 (2, 5)
 (3, 4)
 (3, 5)
 (4, 5)
5 choose 3
 (1, 2, 3)
 (1, 2, 4)
 (1, 2, 5)
 (1, 3, 4)
 (1, 3, 5)
 (1, 4, 5)
 (2, 3, 4)
 (2, 3, 5)
 (2, 4, 5)
 (3, 4, 5)
5 choose 4
 (1, 2, 3, 4)
 (1, 2, 3, 5)
 (1, 2, 4, 5)
 (1, 3, 4, 5)
 (2, 3, 4, 5)
5 choose 5
 (1, 2, 3, 4, 5)