Home > Software design >  How to generate this permutation?
How to generate this permutation?

Time:10-05

This is the numeric permutation I would like to generate --> 1,12,21,123,132,213,... 987654321. I've made so many attempts but honestly I don't know where to start. I've tried using for loops, lists and permutations but it didn't work. So I've tried this:

from itertools import permutations
list = [1,2,3,4,5,6,7,8,9]
for x in list:
    permutations(list,x)
    list2 = list(permutations(list))
    print(list2)

The problem is not how to generate the permutation but to manage the increment of the digits.

Best regards and thank you all!

CodePudding user response:

Note that itertools.permutations returns permutations of all the same length (controlled by the r parameter, or the length of the iterable if r is None.) Based on that, the key is to recognize that what you are actually looking for is the union of multiple sets of permutations.

Here's one way we could get that:

from itertools import permutations
digits = [1,2,3,4,5,6,7,8,9]
result = []
for result_size in range(1, len(digits)   1):
    digits_slice = digits[:result_size]
    result.extend(permutations(digits_slice))
print(result)
# [(1,), (1, 2), (2, 1), (1, 2, 3), (1, 3, 2), (2, 1, 3), (2, 3, 1), (3, 1, 2), (3, 2, 1), (1, 2, 3, 4), (1, 2, 4, 3), ...]

Note: You should never use list as a variable name, because it shadows the built-in list type. I renamed list to digits to avoid this problem.

If you want the items in the result list to be ints instead of tuples, you can add:

result = [int(''.join(str(i) for i in tup)) for tup in result]
print(result)
# [1, 12, 21, 123, 132, 213, 231, 312, 321, 1234, 1243, ...]

CodePudding user response:

Try not to shadow python keywords. You could try something like this:

from itertools import permutations
lst = [str(i) for i in range(10)]

for i in range(1,len(lst) 1):
    sub_list = lst[0:i]
    g = ("".join(perm) for perm in permutations(sub_list))
    # print(list(g))

Feel free to uncomment the print statement.

  • Related