Skip to content

Instantly share code, notes, and snippets.

@junkmechanic
Created November 10, 2013 16:09
Show Gist options
  • Save junkmechanic/7400065 to your computer and use it in GitHub Desktop.
Save junkmechanic/7400065 to your computer and use it in GitHub Desktop.
Alternative (not really!) to itertools.permutations. Sweet recursive indulgence. However, due to lack of in-built support for TRE in Python, this is a slow implementation. So please do not try this at home.
# inspired by the algorithm to find all possible strings from a given
# set of alphabets (as in the function permute here)
# the execution time is compared with itertools.permutations
def permute(lst):
if len(lst) < 2:
yield lst
else:
for perm in permute(lst[1:]):
for i in range(len(lst)):
yield(perm[:i] + lst[0] + perm[i:])
def combine(lst, r):
if r == 1:
for i in lst:
yield i
else:
for i in range(len(lst)):
for comb in combine(lst[i + 1:], r - 1):
yield(lst[i] + comb)
def permutate(lst, r):
for item in combine(lst, r):
for out in permute(item):
yield out
if __name__ == '__main__':
for item in permutate(['a', 'b', 'c', 'd'], 2):
print item
from timeit import timeit
print(timeit("permutate(['a', 'b', 'c', 'd'], 2)",
setup="from __main__ import permutate", number=1000))
print(timeit("permutations(['a', 'b', 'c', 'd'], 2)",
setup="from itertools import permutations", number=1000))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment