Reputation: 135
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?
Upvotes: 2
Views: 754
Reputation: 7931
itertools.permutations
takes an iterable and returns an iterator yielding tuples.
Use join()
that return a string which is the concatenation of the strings in the iterable iterable
join()
DOCS,
itertools.permutations
DOCS
Use this:
import itertools
for x in itertools.permutations("1234"):
print (''.join(x))
Output:
1234
1243
1324
1342
1423
1432
2134
2143
2314
2341
....
Upvotes: 3
Reputation: 13693
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']
Upvotes: 5
Reputation: 6033
see itertools.permutations return tuple. see join function:
In [1]: ''.join(('1','2','3'))
Out[1]: '123'
try this:
for x in itertools.permutations("1234"):
print ''.join(x)
Upvotes: 2