Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Iterative solution for :- Finding String permutations

I read this simple and elegant python solution for finding all permutations of a given string. It is recursive. Based on that I tried to implement an iterative solution in python.

Below is my code. But it works only for 3 character strings :( Stuck trying to see how the recursion base case condition and recursion condition translates into iterative(non-recursive) Any pointers would help to get a iterative solution working.(Either based on this algorithm or any other)

def  permutations_iter(word):
while True:
    perms = []
    result = []

    char = word[0]
    new_word = word[1:]

    if len(new_word)==2: 
        perms = [new_word,''.join(reversed(new_word))]

    for perm in perms: 
        #insert the character into every possible location 
        for i in range(len(perm)+1): 
            result.append(perm[:i] + char + perm[i:]) 
    return result

    if len(new_word)==2:
        break;


   #example code to call this iterative function        
   print permutations_iter("LSE")   
like image 268
goldenmean Avatar asked Aug 14 '13 09:08

goldenmean


People also ask

How do you find the permutation of a string?

We can find the count without finding all permutation. Idea is to find all the characters that is getting repeated, i.e., frequency of all the character. Then, we divide the factorial of the length of string by multiplication of factorial of frequency of characters.

How do you find all permutations of string without recursion?

For example, for <A,B,C>, the swap sequence 012 leaves all items in place, while 122 starts by swapping index 0 with index 1, then swaps 1 with 2, and then swaps 2 with 2 (i.e. leaves it in place). This results in the permutation BCA.

What is permutation of string in Java?

Permutation of the string means all the possible new strings that can be formed by interchanging the position of the characters of the string. For example, string ABC has permutations [ABC, ACB, BAC, BCA, CAB, CBA].


1 Answers

You can convert every recursion to an iteration using a stack. But in this case it's even simpler since the algorithm is very simple.

def perms(word):
    stack = list(word)
    results = [stack.pop()]
    while len(stack) != 0:
        c = stack.pop()
        new_results = []
        for w in results:
            for i in range(len(w)+1):
                new_results.append(w[:i] + c + w[i:])
        results = new_results
    return results

For a more general conversion of recursion to iteration with a stack read this

like image 137
Viktor Kerkez Avatar answered Oct 17 '22 04:10

Viktor Kerkez