permutations of string

I happen to see an movie where police inspector gets a jumbled word as clue , he writes all permutations
of string on paper. so I wrote an algorithm/python program so that it returns all permutations of given string. atleast now the police officer will save his time :) hehe just kidding .

here is the python program.

how to execute this ?
python ./permutations  "word"

'''
Created on Apr 29, 2012

@author: vedara
'''
import sys
if(len(sys.argv) < 2):
    print "enter ./permutations.py "
    exit(0)
 
s=str(sys.argv[1])
out=[]
s_len=len(s)
used=[]

 
def permute(in_s1,out,used,length,reclength):
    i=0
 
    if(reclength==length):
        output=""
        print(output.join(out))
         

    while i < length:
     
        if(used[i]):
            i=i+1
            continue
     
        out[reclength]=in_s1[i]
        used[i]=1
        permute(in_s1,out,used,length,reclength+1)
        used[i]=0    
        i=i+1
   
for i in s:
    out.append(i)
 
i=0

while i < len(s):
    used.append(0)
    i=i+1
   
permute(s,out,used,len(s),0)
out=[]
used=[]

email me if indentation of program changes...if indentation changes program wont compile in python.. 

example : python permutations.py hey

output:
 hey 
 hye
 ehy
 eyh
 yhe
 yeh

No comments: