I’m trying to create a program in python which generates all the possible combinations (non-repeating) for a given number
If the input is “123”, Output should be
JavaScript
x
6
1
123,132,213,231,312,321
2
3
12,13,21,23,31,32
4
5
1,2,3
6
My current code is
JavaScript
1
7
1
import itertools
2
3
a=[1,2,3]
4
5
for i in range(1,len(a)+1):
6
print(list(itertools.combinations(a,i)))
7
Advertisement
Answer
You can use itertools.permutations
:
JavaScript
1
8
1
import itertools
2
3
def permute_all(value):
4
return [''.join(permutation) for i in range(len(value)) for permutation in itertools.permutations(value, i+1)]
5
6
print(permute_all('123'))
7
# Outputs ['1', '2', '3', '12', '13', '21', '23', '31', '32', '123', '132', '213', '231', '312', '321']
8