Dan
0
Q:

permutations python

>>> from itertools import permutations
>>> perm = permutations([1, 2, 3])
>>> for i in list(perm): 
...     print(i)
... 
(1, 2, 3)
(1, 3, 2)
(2, 1, 3)
(2, 3, 1)
(3, 1, 2)
(3, 2, 1)
0
# A Python program to print all  
# permutations using library function 
from itertools import permutations 
  
# Get all permutations of [1, 2, 3] 
perm = permutations([1, 2, 3]) 
  
# Print the obtained permutations 
for i in list(perm): 
    print i 
3
import itertools
print(list(itertools.permutations([1,2,3])))
3
# 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
1

New to Communities?

Join the community