-
-
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.
This file contains hidden or 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
# 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