python permutations
# Python program to print all permutations using
# Heap's algorithm
# Prints the array
def printArr(a, n):
for i in range(n):
print(a[i], end=" ")
print()
# Generating permutation using Heap Algorithm
def heapPermutation(a, size, n):
# if size becomes 1 then prints the obtained
# permutation
if size == 1:
printArr(a, n)
return
for i in range(size):
heapPermutation(a, size - 1, n)
# if size is odd, swap 0th i.e (first)
# and (size-1)th i.e (last) element
# else If size is even, swap ith
# and (size-1)th i.e (last) element
if size & 1:
a[0], a[size - 1] = a[size - 1], a[0]
else:
a[i], a[size - 1] = a[size - 1], a[i]
# Driver code
a = [1, 2, 3]
n = len(a)
heapPermutation(a, n, n)
# This code is contributed by ankush_953
def permutations(iterable, r=None):
# permutations('ABCD', 2) --> AB AC AD BA BC BD CA CB CD DA DB DC
# permutations(range(3)) --> 012 021 102 120 201 210
pool = tuple(iterable)
n = len(pool)
r = n if r is None else r
if r > n:
return
indices = list(range(n))
cycles = range(n, n-r, -1)
yield tuple(pool[i] for i in indices[:r])
while n:
for i in reversed(range(r)):
cycles[i] -= 1
if cycles[i] == 0:
indices[i:] = indices[i+1:] + indices[i:i+1]
cycles[i] = n - i
else:
j = cycles[i]
indices[i], indices[-j] = indices[-j], indices[i]
yield tuple(pool[i] for i in indices[:r])
break
else:
return