Created
September 1, 2022 18:44
-
-
Save ravichandrae/494ef73627ec0554cfa618e2ab322838 to your computer and use it in GitHub Desktop.
Given a list, generate all permutations of the items in it.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def permutations(lst): | |
return permutations_util(lst, 0) | |
def permutations_util(lst, index): | |
perms = [] | |
if index == len(lst) - 1: | |
perms.append(lst.copy()) | |
for i in range(index, len(lst)): | |
lst[i], lst[index] = lst[index], lst[i] | |
perms.extend(permutations_util(lst, index+1)) | |
lst[i], lst[index] = lst[index], lst[i] | |
return perms | |
num_list = [1, 2, 3] | |
print(permutations(num_list)) | |
char_list = ['r', 'a', 'm'] | |
print(permutations(char_list)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment