Permutations and combinations in Python

In this article, I will show you how we can enumerate permutations and combinations in Python using iteration. If you prefer R than Python, please look at this blog post. And if you are not familiar with permutations and combinations, I invite you to read my first post. Indeed, you will find there a definition, an example and the formulas to compute the number of possibilities depending on order dependence and replacement allowance.

In the four next sections, we will use r loops to generate all the possible subsets of r elements from a given set of n elements in Python 3.

cheat sheet of the permutations and combinations in Python using iteration
Cheat sheet of the permutations and combinations in Python using iteration

Variables assignment

animals = ["horses", "donkeys", "dogs", "cats", "ferrets"]
n = len(animals)

Permutations with repetition

r = 2

for i in range(0, n):
    for j in range(0, n):
        print(animals[i], "-", animals[j])

r = 3

for i in range(0, n):
    for j in range(0, n):
        for k in range(0, n):
            print(animals[i], "-", animals[j], "-", animals[k])

Permutations without repetition

r = 2

for i in range(0, n):
    for j in set(range(0, n))-set([i]):
        print(animals[i], "-", animals[j])

r = 3

for i in range(0, n):
    for j in set(range(0, n))-set([i]):
        for k in set(range(0, n))-set([i, j]):
            print(animals[i], "-", animals[j], "-", animals[k])

Combinations with repetition

r = 2

for i in range(0, n):
    for j in range(i, n):
        print(animals[i], "-", animals[j])

r = 3

for i in range(0, n):
    for j in range(i, n):
        for k in range(j, n):
            print(animals[i], "-", animals[j], "-", animals[k])

Combinations without repetition

r = 2

for i in range(0, n):
    for j in set(range(i, n))-set([i]):
        print(animals[i], "-", animals[j])

r = 3

for i in range(0, n):
    for j in set(range(i, n))-set([i]):
        for k in set(range(j, n))-set([i, j]):
            print(animals[i], "-", animals[j], "-", animals[k])

Conclusion

In conclusion, the implementation of the four cases is also possible in Python 3. But in my opinion, it was difficult to remove elements from the list created by the range function. The setdiff function from base R is more straightforward! Is this blog post helpful to you?

Related posts

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply