Search
 
SCRIPT & CODE EXAMPLE
 

PYTHON

How to generate all the permutations of a set of integers, in Python?

"""
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 any item in list is in anoter list 
Python :: how to get username with userid discord.py 
Python :: pandas count the number of unique values in a column 
Python :: python verzeichnis erstellen 
Python :: python cheat sheet 
Python :: python how to change back to the later directory 
Python :: how to delete a file in python 
Python :: how to earse special chrat¥cter from string in python 
Python :: scikit learn lda 
Python :: find the most similar rows in two dataframes 
Python :: sqlite query in python 
Python :: python file reading 
Python :: sort a string in python 
Python :: python check if int 
Python :: generate list of consecutive numbers 
Python :: python check if 3 values are equal 
Python :: pandas merge on index column 
Python :: python list.peek 
Python :: turn df to dict 
Python :: python find index by value 
Python :: como leer lineas de un archivo de texto en python 
Python :: replace string if it contains a substring pandas 
Python :: python library to make qr codes 
Python :: import excel python 
Python :: pandas drop column in dataframe 
Python :: delete all elements in list python 
Python :: how to url encode using python django 
Python :: fill zero behind number python 
Python :: python list unique in order 
Python :: python set remove if exists 
ADD CONTENT
Topic
Content
Source link
Name
3+4 =