fork download
  1. def choose(n, k):
  2. if k == 0:
  3. yield ()
  4. return
  5. if n < k:
  6. return
  7. for r in choose(n-1,k-1):
  8. yield (True,) + r
  9. for r in choose(n-1,k):
  10. yield (False,) + r
  11.  
  12. def compress(seq1, seq2):
  13. ''' yeild seq1 values where seq2 is true '''
  14. i1, i2 = iter(seq1), iter(seq2)
  15. while i1 and i2:
  16. val = i1.next()
  17. if i2.next():
  18. yield val
  19.  
  20. def combinations(seq, k):
  21. for choice in choose(len(seq), k):
  22. yield tuple(compress(seq, choice))
  23.  
  24. sequence = (50,60,70,80,90)
  25. k = 3
  26. for combination in combinations(sequence,k):
  27. print combination
  28.  
Success #stdin #stdout 0.01s 7852KB
stdin
Standard input is empty
stdout
(50, 60, 70)
(50, 60, 80)
(50, 60, 90)
(50, 70, 80)
(50, 70, 90)
(50, 80, 90)
(60, 70, 80)
(60, 70, 90)
(60, 80, 90)
(70, 80, 90)