Skip to content

Instantly share code, notes, and snippets.

@ravichandrae
Created September 1, 2022 18:44
Show Gist options
  • Save ravichandrae/494ef73627ec0554cfa618e2ab322838 to your computer and use it in GitHub Desktop.
Save ravichandrae/494ef73627ec0554cfa618e2ab322838 to your computer and use it in GitHub Desktop.
Given a list, generate all permutations of the items in it.
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