# Permutations in Python

PythonServer Side ProgrammingProgramming

Suppose we have a collection of distinct integers; we have to find all possible permutations. So if the array is like [2,1,3], then the result will be [[1,2,3], [1,3,2], [2,1,3], [2,3,1], [3,1,2], [3,2,1]]

To solve this, we will follow these steps −

• We will use the recursive approach, this will make the list, start, curr and res
• if start > length of list – 1, then add curr into the res, and return
• for i in range start to length of given list – 1
• swap the elements of list present at index start and (start + (i – start))
• permutation(list, start + 1, curr + [list[start]], res)
• swap the elements of list present at index start and (start + (i – start))
• initially call the permutation(arr, 0, [], res)

## Example(Python)

Let us see the following implementation to get a better understanding −

Live Demo

class Solution(object):
def permute(self, nums):
result = []
self.permute_util(nums,0,[],result)
return result
def permute_util(self,given_list,start,curr,result):
if start > len(given_list)-1:
#print(curr)
result.append(curr)
return
for i in range(start,len(given_list)):
self.swap(given_list,start,start+(i-start)) self.permute_util(given_list,start+1,curr+[given_list[start]],result)
#print(given_list)
self.swap(given_list, start, start + (i - start))
def swap(self,nums,index1,index2):
temp = nums[index1]
nums[index1] = nums[index2]
nums[index2] = temp
ob1 = Solution()
print(ob1.permute([1,2,3,4]))

## Input

[1,2,3,4]

## Output

[[1,2,3,4],[1,2,4,3],[1,3,2,4],[1,3,4,2],[1,4,3,2],[1,4,2,3],[2,1,3,4],[2,1,4,3],[2,3,1,4],[2,3,4,1],[2,4,3,1],[2,4,1,3],[3,2,1,4],[3,2,4,1],[3,1,2,4],[3,1,4,2],[3,4,1,2],[3,4,2,1],[4,2,3,1],[4,2,1,3],[4,3,2,1],[4,3,1,2],[4,1,3,2],[4,1,2,3]]
Updated on 27-Apr-2020 13:18:41

Advertisements
{"found_math": true, "script_math_tex": 0, "script_math_asciimath": 0, "math_annotations": 0, "math_alttext": 0, "mathml": 0, "mathjax_tag": 0, "mathjax_inline_tex": 0, "mathjax_display_tex": 0, "mathjax_asciimath": 1, "img_math": 0, "codecogs_latex": 0, "wp_latex": 0, "mimetex.cgi": 0, "/images/math/codecogs": 0, "mathtex.cgi": 0, "katex": 0, "math-container": 0, "wp-katex-eq": 0, "align": 0, "equation": 0, "x-ck12": 0, "texerror": 0, "url": "https://www.tutorialspoint.com/permutations-in-python", "fetch_time": 1656189419000000000, "content_mime_type": "text/html", "warc_filename": "crawl-data/CC-MAIN-2022-27/segments/1656103036099.6/warc/CC-MAIN-20220625190306-20220625220306-00190.warc.gz", "warc_record_offset": 1127103349, "warc_record_length": 8583, "token_count": 641, "char_count": 1821, "score": 3.53125, "int_score": 4, "crawl": "CC-MAIN-2022-27", "snapshot_type": "latest", "language": "en", "language_score": 0.5487581491470337, "file_path": "/sailhome/yjruan/project/latent-lm/data/processed/finemath-4plus/finemath-4plus/train-00014-of-00064.parquet"}