0

So I ran into this problem recently and I am pretty stumped into getting itertools to work happily.

The Problem

Lets say I have a list of six elements:

elements = ["A", "B", "C", "D", "E", "F", "G"]

And I want to generate all combinations of the list with a random size (1-max_length_of_elements) with a function.

def generate_combinations(elements, size_of_combinations = 6):
    import itertools
    combinations = itertools.combinations(elements, size_of_combinations)
    return list(combinations)

What happens is that I get back is this

[
    ('A', 'B', 'C', 'D', 'E', 'F'),
    ('A', 'B', 'C', 'D', 'E', 'G'), 
    ('A', 'B', 'C', 'D', 'F', 'G'), 
    ('A', 'B', 'C', 'E', 'F', 'G'), 
    ('A', 'B', 'D', 'E', 'F', 'G'),
    ('A', 'C', 'D', 'E', 'F', 'G'), 
    ('B', 'C', 'D', 'E', 'F', 'G')

]

Which to me is a little odd because it seems to actually do combinations but with a restriction that the elements have to be in order.

So I wonder if there is a simple method into making itertools combinations work with generating all unsorted combinations.

Or is there perhaps another method I can follow.

Suliman Sharif
  • 607
  • 1
  • 9
  • 26
  • 2
    A combination is defined as an unordered subset. If you want the combinations each in every possible order, then you want each **permutation**. Use `itertools.permutations` instead. – kaya3 Nov 22 '19 at 05:06
  • 1
    Possible duplicate of [How to generate all permutations of a list in Python](https://stackoverflow.com/questions/104420/how-to-generate-all-permutations-of-a-list-in-python) – kaya3 Nov 22 '19 at 05:07
  • Damn that was so good. Thank you – Suliman Sharif Nov 22 '19 at 05:10

0 Answers0