Home How to generate all permutations of a list in Python
Post
Cancel

How to generate all permutations of a list in Python

This post is intended to be different than my usual posts, and it’s meant to show that a person should also have fun with programming.

So recently while my girlfriend was reading the newspaper, she came across with a challenge that had the following premise:

1
Pick 3 numbers from the following image whose total must be equal to 306

Ok, so I thought. It’s been a while since I’ve ran the python cli and just mess with the interpreter to find out things quickly (I love python for this sort of stuff :D )

So, the answer to the above example is clearly based on the sum of permutations of choosing 3 numbers.

By using python 3 itertools, we may use it to create a generator containing all permutations of a given R (size).

The function signature we are looking for in itertools is as follows:

1
itertools.permutations(List, R)

So let’s start by setting the values above to a list:

1
ls = [58, 48, 80, 27, 144, 67, 154, 38, 79, 34, 83, 121, 36, 172, 99, 73]

Ok, so now let’s create all the permutations in it:

1
permutations_generator = itertools.permutations(ls, 3)

Ok, so we need to iterate for all elements and find out their sum.

List object is perfect for this, and its easy to cast the values to list.

1
permutations_list = list(permutations_generator)

So, now all we need to do is iterate all elements and just use the function sum on each of the permutations we generated before.

1
2
3
for el in permutations_list:
    if(sum(el) == 306):
        print(el)

And by running this through our interpreter in the command line we should get the following:

1
2
3
4
5
6
7
8
9
10
11
12
(144, 79, 83)
(144, 83, 79)
(154, 79, 73)
(154, 73, 79)
(79, 144, 83)
(79, 154, 73)
(79, 83, 144)
(79, 73, 154)
(83, 144, 79)
(83, 79, 144)
(73, 154, 79)
(73, 79, 154)

And that’s it, out of curiosity, if you do this by hand, without optimizing our permutations to sets for instance (we are not going for optimization for such a small set) you would end up with:

1
2
>>>len(permutations_list)
3360

That’s a lot of number crunching to be done by hand :D

And that’s it. Hope on that side you also like to solve this small things using your language of choice.

This post is licensed under CC BY 4.0 by the author.