Coding, Python

Python fun #4: Create sorted list of all possible numbers using same digits (of a number)

Let’s say the number is 123.

Then the statement:

[int(''.join(x)) for x in permutations(list(str(123)))]

will create a sorted list of all possible numbers using ‘1’,’2′ and ‘3’.
which is, [123, 132, 213, 231, 312, 321]

What it is doing

The part, permutations(list(str(‘123’ is creating a permutated tuple list of splitted string ‘123’.
And the int(”.join(x)) is converting each tuple to back to Integer.

However, you need to

import permutations from itertools

so, the generalized version would be:

import permutations from itertools
[int(''.join(x)) for x in list(permutations(list(str(n))))]
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s