Follow this blog by Email

Sunday, 18 August 2013

String permutations - Solution

Here is a iterative solution to the problem asked here few days back:
Find all permutations of a given string.

def permutations_iter(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  

 #Example test code  
 print permutations_iter("ABC") 

No comments: