Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to generate this permutation?

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!

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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 idx in range(len(digits)):
    result_size = idx + 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, ...]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading