A fully recursive function should be:
def permutations_comp_recursive(first, last, perms, i):
if len(first) == 0:
perms.append(last)
elif i == len(first):
pass
else:
permutations_comp_recursive(first, last, perms, i+1)
if first:
permutations_comp_recursive(
first[:i]+first[i+1:],
last + [first[i]],
perms, 0)
For good performance i recommand numpy solutions.
Edit 1: Now the following should be tail-recursive, with the use of list comprehensions. This uses a workarount for tail-recursion in python (and the last 2 arguments were omitted - the result is passed as return value):
import itertools as it
class Recurse(Exception):
def __init__(self, *args, **kwargs):
self.args = args
self.kwargs = kwargs
def recurse(*args, **kwargs):
raise Recurse(*args, **kwargs)
def tail_recursive(f):
def decorated(*args, **kwargs):
while True:
try:
return f(*args, **kwargs)
except Recurse as r:
args = r.args
kwargs = r.kwargs
continue
return decorated
@tail_recursive
def permutations_tail_recursive(first, last, direct=False):
if len(first) == 0 or not all(first):
return last
else:
l = len(first[0]) if direct else len(first)
if last:
return recurse([fi[:i]+fi[i+1:] for fi, i in it.product(first, range(l))],
[last[j] + first[j][i] for j, i in it.product(range(len(last)), range(l))], True)
else:
return recurse([first[:i]+first[i+1:] for i in range(l)],
[first[i] for i in range(l)], True)
This is not optimised and uses loops. Im not sure if this and the code without loop above can be combined - might look into it again.
itertools.permutations can be used for this application.