fork download
  1. elements = [1,2,3,4,5,6]
  2. combinations = []
  3. k = 3
  4.  
  5. def get_combinations_BFS():
  6. queue = [([],0)]
  7. while queue:
  8. combination, elem_idx = queue.pop()
  9.  
  10. if elem_idx == len(elements):
  11. continue
  12.  
  13. new_comb = combination[:]
  14. new_comb.append(elements[elem_idx])
  15.  
  16. if len(new_comb) == k:
  17. combinations.append(new_comb)
  18.  
  19. queue.append((combination, elem_idx+1))
  20. queue.append((new_comb, elem_idx+1))
  21.  
  22. get_combinations_BFS()
  23.  
  24.  
  25. print(combinations)
Success #stdin #stdout 0.01s 118784KB
stdin
Standard input is empty
stdout
[[1, 2, 3], [1, 2, 4], [1, 2, 5], [1, 2, 6], [1, 3, 4], [1, 3, 5], [1, 3, 6], [1, 4, 5], [1, 4, 6], [1, 5, 6], [2, 3, 4], [2, 3, 5], [2, 3, 6], [2, 4, 5], [2, 4, 6], [2, 5, 6], [3, 4, 5], [3, 4, 6], [3, 5, 6], [4, 5, 6]]