1# A Python program to print all permutations using library function
2from itertools import permutations
3perm = permutations([1, 2, 3])
4for i in list(perm):
5 print (i)
6# (1, 2, 3)
7# (1, 3, 2)
8# (2, 1, 3)
9# (2, 3, 1)
10# (3, 1, 2)
11# (3, 2, 1)
1import itertools
2
3a = [1, 2, 3]
4n = 3
5
6perm_iterator = itertools.permutations(a, n)
7
8for item in perm_iterator:
9 print(item)
1def permutations(iterable, r=None):
2 # permutations('ABCD', 2) --> AB AC AD BA BC BD CA CB CD DA DB DC
3 # permutations(range(3)) --> 012 021 102 120 201 210
4 pool = tuple(iterable)
5 n = len(pool)
6 r = n if r is None else r
7 if r > n:
8 return
9 indices = list(range(n))
10 cycles = list(range(n, n-r, -1))
11 yield tuple(pool[i] for i in indices[:r])
12 while n:
13 for i in reversed(range(r)):
14 cycles[i] -= 1
15 if cycles[i] == 0:
16 indices[i:] = indices[i+1:] + indices[i:i+1]
17 cycles[i] = n - i
18 else:
19 j = cycles[i]
20 indices[i], indices[-j] = indices[-j], indices[i]
21 yield tuple(pool[i] for i in indices[:r])
22 break
23 else:
24 return
25print ( list(permutations([1, 2, 3], 2)) )
26# [(1, 2), (1, 3), (2, 1), (2, 3), (3, 1), (3, 2)]
1def combinations(iterable, r):
2 pool = tuple(iterable)
3 n = len(pool)
4 for indices in permutations(range(n), r):
5 if sorted(indices) == list(indices):
6 yield tuple(pool[i] for i in indices)