R. Javid
0
Q:

python permutations

>>> 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
from itertools import permutations 
l = list(permutations(range(1, 4))) 
print l 
0
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
0

New to Communities?

Join the community