Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
from collections import deque
def permutations(word):
if len(word) == 1:
return [word]
perms = permutations(word[1:])
c = word[0]
res = []
L = len(perms[0]) + 1
for perm in perms:
for i in range(L):
res.append(perm[:i] + c + perm[i:])
return res
def permutations_iter(word):
if len(word) == 1:
return [word]
stack = deque(word)
res = [stack.pop()]
while stack:
c = stack.pop()
next_res = []
L = len(res[0]) + 1
for r in res:
for i in range(L):
next_res.append(r[:i] + c + r[i:])
res = next_res
return res
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.