Skip to content

Instantly share code, notes, and snippets.

@ta1hia
Created May 27, 2016 20:17
Show Gist options
  • Save ta1hia/b011f48499675374d7d85931ca3a2067 to your computer and use it in GitHub Desktop.
Save ta1hia/b011f48499675374d7d85931ca3a2067 to your computer and use it in GitHub Desktop.
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