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!
>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, ...]