Search
 
SCRIPT & CODE EXAMPLE
 

PYTHON

permutations of a set

"""
This implementation demonstrates how 
to generate all the permutations of 
a given set of integers.

Example: 
For following array: [1, 2, 3]
The output would be: 
[[1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1], 
[3, 1, 2], [3, 2, 1]]

Let n be the size of the array.

Time complexity: O(n*n!)
Space complexity: O(n*n!)
"""


def find_permutations(array):
    permutations = []
    generate_permutations(0, array, permutations)
    return permutations


def generate_permutations(idx, array, permutations):
    if idx == len(array) - 1:
        permutations.append(array[:])  # add a copy of array to output
    else:
        for j in range(idx, len(array)):
            swap(array, idx, j)  # swap idxth elem with every other elem
            generate_permutations(idx+1, array, permutations)
            swap(array, j, idx)  # backtrack


def swap(array, i, j):
    array[i], array[j] = array[j], array[i]


# Below outputs:
# [[1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 2, 1], [3, 1, 2]]
print(find_permutations([1, 2, 3]))

"""
# Another solution:
import itertools
# Below output:
# [(1, 2, 3), (1, 3, 2), (2, 1, 3), (2, 3, 1), (3, 1, 2), (3, 2, 1)]
print(list(itertools.permutations([1, 2, 3])))
"""
Comment

PREVIOUS NEXT
Code Example
Python :: how to check if text is in upper case in python 
Python :: how to delete a column from a dataframe in python 
Python :: count unique values pandas 
Python :: pandas change to first day 
Python :: sort dict by values 
Python :: how to change column name in pandas 
Python :: how to delete file in python 
Python :: show multiple plots python 
Python :: python tkinter getting labels 
Python :: how to find which 2 rows of a df are the most similar 
Python :: as type in pandas 
Python :: convert array to set python 
Python :: skip error python 
Python :: Python Requests Library Put Method 
Python :: list to string 
Python :: horizontal bar plot matplotlib 
Python :: get just filename without extension from the path python 
Python :: python merge dictionaries 
Python :: colorbar min max matplotlib 
Python :: index in list 
Python :: python read in integers separated by spaces 
Python :: django.db.utils.ProgrammingError: relation "users" does not exist in django 3.0 
Python :: read from text file and append in list 
Python :: split a variable into multiple variables in python 
Python :: python string to datetime object 
Python :: python time library 
Python :: hstack in numpy 
Python :: how to write post method using flask 
Python :: webdriver firefox install 
Python :: validate ip address python 
ADD CONTENT
Topic
Content
Source link
Name
4+7 =