Thursday 9 January 2014

All permutations of numbers in Python

Just recently, I was looking to fill an excel sheet with all possible permutations of five numbers : 1,2,3,4,5 . One permutation in each cell. The excel sheet was a test case document and each permutation meant to go in each cell was a test case.
I was looking to write permutations in below format.
e.g.
1-->2-->3-->5-->4
Which meant From condition one, code should enter condition 2, then condition 3, then condition 5, then condition 4 which described 1 test case scenario.

Writing all the 120 permutations (5!) by hand was painful. Was looking for getting the permutations printed on screen programmatically.
Turned to python. Python has module itertools which provides lot of functions for various iterators to loop the input data.
But the problem was I was looking output from the permutations logic as below:
1->2->3->4->5 ( 1st permutation of 1,2,3,4,5)
1->2->3->5->4 ( 2nd permutation)
...etc

But this below python code did not gave output as I desired.

import itertools  
 print([x for x in itertools.permutations('12345')])

gives output as
[('1', '2', '3', '4', '5'), ('1', '2', '3', '5', '4'),...

List of tuples of characters.

Then tried
import itertools  
 a=[1,2,3,4,5]  
 print([x for x in itertools.permutations(a)])  

This gave closer output to what I needed but still not exactly what I was looking for

[(1, 2, 3, 4, 5), (1, 2, 3, 5, 4),

List of tuples of numbers

But as I say, if it can be done in life, it can be done using Python:

I coded as below to output of the permutations, exactly as as I wanted:

import itertools  
 a=[1,2,3,4,5]  
 permuted_a = [x for x in itertools.permutations(a)]  
 len_perm = len(permuted_a)  
 for i in range(len_perm):  
   print permuted_a[i][0],'-->',permuted_a[i][1],'-->',permuted_a[i][2],'-->',permuted_a[i][3],'-->',permuted_a[i][4] 

This generated output as below:
1 --> 2 --> 3 --> 4 --> 5
1 --> 2 --> 3 --> 5 --> 4
1 --> 2 --> 4 --> 3 --> 5
1 --> 2 --> 4 --> 5 --> 3
1 --> 2 --> 5 --> 3 --> 4

Just copied the console output from above and pasted to my excel sheet.
One permutation, in one cell of the excel sheet.
Voila! Just works.






6 comments:

Anonymous said...

why do you have so awful for loops?
instead use something like this:
for p in permuted_a:
print ' --> '.join([str(tp) for tp in p[1:]])

Anonymous said...

sry, no slices in list comprehension.

Unknown said...

you can re-write this much more efficiently as

for row in itertools.permutations([1,2,3,4,5]): print "-->".join("%s"%v for v in row)

Anonymous said...

for p in itertools.permutations(a):
print ' --> '.join(map(str, p))

Unknown said...

@Unknown - Thanks. Your's sure is a efficient solution.

Anonymous said...

Loops are not necessary:

print '\n'.join(map(' --> '.join, itertools.permutations('12345')))