How to generate all permutations of a string?
Girish Sahani
girish at cse.iitb.ac.in
Thu Jun 22 05:35:39 EDT 2006
> In article <mailman.7352.1150963651.27775.python-list at python.org>,
> "Girish Sahani" <girish at cse.iitb.ac.in> wrote:
>
>> I want to generate all permutations of a string.
>
> def permute(Seq) :
> """generator which yields successive permutations of the elements
> of Seq."""
> if len(Seq) == 0 :
> yield ()
> else :
> for i in range(0, len(Seq)) :
> for rest in permute(Seq[:i] + Seq[i + 1:]) :
> yield (Seq[i],) + rest
> #end for
> #end for
> #end if
> #end permute
thanks lawrence...however this func doesnt return the permuted strings, so
i added some code as follows to generate a list of all the permutations:
def permute(seq):
l = []
if len(seq) == 0:
yield []
else:
for i in range(0,len(seq)):
for rest in permute(seq[:i] + seq[i+1:]):
yield (seq[i],) + rest
for t in permute(seq):
l.append(''.join(t))
return l
This gives me a syntax error!
I need to output a list that has all the permutations of the input string.
> --
> http://mail.python.org/mailman/listinfo/python-list
>
More information about the Python-list
mailing list