Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python permutations

Tags:

python

I am trying to generate pandigital numbers using the itertools.permutations function, but whenever I do it generates them as a list of separate digits, which is not what I want.

For example:

for x in itertools.permutations("1234"):
    print(x)

will produce:

('1', '2', '3', '4')
('1', '2', '4', '3')
('1', '3', '2', '4')
('1', '3', '4', '2')
('1', '4', '2', '3')
('1', '4', '3', '2'), etc.

whereas I want it to return 1234, 1243, 1324, 1342, 1423, 1432, etc. How would I go about doing this in an optimal fashion?

like image 545
ApocalypticNut Avatar asked Apr 10 '26 09:04

ApocalypticNut


1 Answers

A list comprehension with the built-in str.join() function is what you need:

import itertools
a = [''.join(i) for i in itertools.permutations("1234") ]
print(a)

Output:

['1234', '1243', '1324', '1342', '1423', '1432', '2134', '2143', '2314', '2341', '2413', '2431', '3124', '3142', '3214', '3241', '3412', '3421', '4123', '4132', '4213', '4231', '4312', '4321']
like image 125
K DawG Avatar answered Apr 12 '26 21:04

K DawG