Skip to content

Commit 1235309

Browse files
committed
permutation
from LeetCode
1 parent c60c70b commit 1235309

File tree

1 file changed

+37
-0
lines changed

1 file changed

+37
-0
lines changed

list_permutation.py

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
# Learn Python together
2+
""" Given an array nums of distinct integers, return all the possible permutations. """
3+
4+
# Solution 1 using loop and recursive
5+
6+
def permute(nums):
7+
if len(nums)<=1:
8+
return [nums]
9+
result= [] # empty list
10+
# iteration through each item in the list
11+
for i in range(len(nums)):
12+
lis = nums[i] # giving value at index i in lis variable
13+
new_list = nums[:i]+nums[i+1:] # giving in new list all elemts of the list exclude lis
14+
for perm in permute(new_list): # recursive call function for creating permutation
15+
result.append([lis]+perm) # add variables to result
16+
return result
17+
18+
#check
19+
list1 = [1,2,3]
20+
list2 = [0]
21+
print(permute(list1))
22+
# Output -> [[1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 1, 2], [3, 2, 1]]
23+
print(permute(list2))
24+
# Output -> [[0]]
25+
26+
27+
# Solution 2 using itertools library with tuples in the list
28+
from itertools import permutations
29+
30+
def perm_tools(nums):
31+
return list(permutations(nums))
32+
33+
# check
34+
print(perm_tools(list1))
35+
# Output -> [(1, 2, 3), (1, 3, 2), (2, 1, 3), (2, 3, 1), (3, 1, 2), (3, 2, 1)]
36+
print(perm_tools(list2))
37+
# Output -> [(0,)]

0 commit comments

Comments
 (0)