popeye
popeye

Reputation: 886

reorder digits of an integer

Suppose I have an integer (say 235) and I want to reorder this number in all possible ways and get all other integers in a list or tuple. Is there a way to do it in python? The desired output will consist of: [235, 253, 325, 352, 523, 532]

And any other if I missed some.

I wanna create a list tuple or any other thing of all these values from where I can use these values somewhere else.

Upvotes: 1

Views: 1925

Answers (4)

user10703542
user10703542

Reputation:

You can use itertools.permutations:

import itertools
list(map(int,map("".join,itertools.permutations("235"))))

https://docs.python.org/3.5/library/itertools.html#itertools.permutations

Upvotes: 0

LordOfThunder
LordOfThunder

Reputation: 310

Use itertools.permutation, one-liners are good to show that you know python very well, but what actually matters is the maintainability. Here is a maintainable code, where every function is doing a single work and after reading the code we can get the logic(wherein the case of a one-liner, we need to spend time understanding the code):

from itertools import permutations as perm

def to_int(p):
    return int(''.join(map(str, p)))

def all_perms(n):
    digits = list(map(int, str(n)))
    perms = []
    for p in perm(digits, len(digits)):
        perms.append(to_int(p))
    return perms

n = 235
print(all_perms(n))

Upvotes: 0

Alexander
Alexander

Reputation: 109520

Convert the number to a string, then use a list comprehension to extract each digit as a character. This gives you the list of digit strings, e.g. ['2', '3', '5'].

Use permutations to get the different arrangements, joining the result and converting them back to integers.

from itertools import permutations

integer = 235
numbers = [i for i in str(integer)]  # ['2', '3', '5']

>>> list(int(''.join(p)) for p in permutations(numbers))
[235, 253, 325, 352, 523, 532]

# Or just simply (no need for `numbers`):
# list(int(''.join(p)) for p in permutations(str(integer)))

Upvotes: 2

Zaraki Kenpachi
Zaraki Kenpachi

Reputation: 5730

Convert number into list of string numbers then do permutations.

import itertools
number = 235
results = [int("".join(x)) for x in list(itertools.permutations(list(str(number))))]

Output:

[235, 253, 325, 352, 523, 532]

Upvotes: 4

Related Questions