Search code examples
pythonalgorithmrecursioncomputer-sciencetail-recursion

Replacing a for loop with tail recursion in a recursive function


I'm trying to make the following function completely tail recursive, e.g. get that pesky for loop out of there. Reason being is that I'm trying to easily convert the solution to an iterative one involving the use of an explicit stack. Please advise.

def permutations(A):
    P = []
    P2 = []
    permutations_recursive(A, [], P)
    permutations_tail_recursive(A, [], P2, 0)
    print(P2)
    return P

def permutations_recursive(first, last, perms):
    if len(first) == 0:
        perms.append(last)
    else:
        for i in range(len(first)):
            permutations_recursive(
                first[:i] + first[i+1:],
                last + [first[i]],
                perms)

Solution

  • Close iterative analog:

    def permutations(A):
        P = []
        permutationsI(A, P)
        print(P)
    
    def permutationsI(A, perms):
       stack = [(A, [])]
        while len(stack):
            first, last = stack.pop()
            if len(first):
                for i in range(len(first)):
                    stack.append((first[:i] + first[i+1:],last + [first[i]]))
            else:
                perms.append(last)
    
    permutations([1,2,3])
    >>[[3, 2, 1], [3, 1, 2], [2, 3, 1], [2, 1, 3], [1, 3, 2], [1, 2, 3]]