What is the relationship between the product function and the concept of permutations with repetitions?

Advertisements
from itertools import permutations,product,combinations_with_replacement

colours = ['r','g','b']

y = list(product(colours,repeat =2 ))
x = list(combinations_with_replacement(colours,2))
print(y)
print(x)

I understand permutation of a set of objects is an ordering of those objects. When some of those objects are identical, the situation is transformed into permutations with repetition.

>Solution :

This may provide some insight:

colours = ['r','g','b']

y = list(product(colours,repeat =2 ))
x = list(combinations_with_replacement(colours,2))
z = [v for v in y if colours.index(v[0]) <= colours.index(v[1])]
print(y)
print(x)
print(z)

Output:

[('r', 'r'), ('r', 'g'), ('r', 'b'), ('g', 'r'), ('g', 'g'), ('g', 'b'), ('b', 'r'), ('b', 'g'), ('b', 'b')]
[('r', 'r'), ('r', 'g'), ('r', 'b'), ('g', 'g'), ('g', 'b'), ('b', 'b')]
[('r', 'r'), ('r', 'g'), ('r', 'b'), ('g', 'g'), ('g', 'b'), ('b', 'b')]

In other words, product provides all possible sequences with repetition, whereas combinations_with_replacement will (in your example) consider g, b and b, g to be equivalent and includes only g, b.

We can replicate combinations_with_replacement by filtering out equivalent permutations from product, as is done with z above.

Leave a ReplyCancel reply