1

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.

LordOfThunder
  • 310
  • 1
  • 3
  • 17
  • Does this answer your question? [Turn a single number into single digits Python](https://stackoverflow.com/questions/21270320/turn-a-single-number-into-single-digits-python) – wondercoll Feb 01 '20 at 17:55
  • I would suggest turning the number into a string and using itertools permutations. – jawsem Feb 01 '20 at 17:56

4 Answers4

4

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]
Zaraki Kenpachi
  • 5,510
  • 2
  • 15
  • 38
2

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)))
Alexander
  • 105,104
  • 32
  • 201
  • 196
0

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

0

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))
LordOfThunder
  • 310
  • 1
  • 3
  • 17