Svinthe
Svinthe

Reputation: 63

Is there a Python function that finds all k-length orderings of a list?

I don't believe this precise question has been asked before. I was recently faced with a problem where I had to find just such a set. An example would probably help:-

Given some list:

list1 = ['a', 'b']

Is there a function that returns the following set?

output = {('a', 'b'), ('a', 'a'), ('b', 'b'), ('b', 'a')}

I have been able to generate the desired output using the itertools combinations_with_replacement and permutations functions, as follows:

from itertools import combinations_with_replacement, permutations
set1 = set(combinations_with_replacement(['a', 'b'], 2))
set2 = set(permutations(['a', 'b'], 2))

>>> set1
{('a', 'b'), ('a', 'a'), ('b', 'b')}
>>> set2
{('b', 'a'), ('a', 'b')}

set1.update(set2)

>>> set1
{('a', 'b'), ('a', 'a'), ('b', 'b'), ('b', 'a')}

Is there a name for such a set? Is there an alternative method I can use?

Upvotes: 2

Views: 45

Answers (2)

Kevin Troy
Kevin Troy

Reputation: 432

Itertools.product() does what you want:

mylist = ['a', 'b']
list(itertools.product(mylist, repeat=2))

Out[8]: [('a', 'a'), ('a', 'b'), ('b', 'a'), ('b', 'b')]

Upvotes: 2

L3viathan
L3viathan

Reputation: 27333

You want itertools.product:

>>> import itertools
>>> set(itertools.product(list1, repeat=2))
{('a', 'b'), ('b', 'a'), ('b', 'b'), ('a', 'a')}

itertools.product with the repeat parameter is essentially "permutations_with_replacement", which seems to be what you want.

Upvotes: 5

Related Questions