fork download
  1. # https://stackoverflow.com/a/75408780/1468366
  2.  
  3. def next_combination(n: int, c: list[int]):
  4. """Compute next combination, in lexicographical order.
  5.  
  6. Args:
  7. n: the number of items to choose
  8. from.
  9. c: a list of integers between 0
  10. (inclusive) and n (exclusive) in
  11. strictly ascending order. It
  12. will get modified by the call.
  13. Returns: the list c after modification,
  14. or None if this was the last
  15. combination.
  16. """
  17. i = len(c)
  18. while i > 0:
  19. i -= 1
  20. n -= 1
  21. if c[i] == n: continue
  22. c[i] += 1
  23. for j in range(i + 1, len(c)):
  24. c[j] = c[j - 1] + 1
  25. return c
  26. return None
  27.  
  28. lst = [0, 1, 2]
  29. while lst is not None:
  30. print(lst)
  31. lst = next_combination(5, lst)
Success #stdin #stdout 0.03s 9612KB
stdin
Standard input is empty
stdout
[0, 1, 2]
[0, 1, 3]
[0, 1, 4]
[0, 2, 3]
[0, 2, 4]
[0, 3, 4]
[1, 2, 3]
[1, 2, 4]
[1, 3, 4]
[2, 3, 4]