How to generate all permutations of a string?

Girish Sahani girish at cse.iitb.ac.in
Thu Jun 22 21:42:10 EDT 2006


>> 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
>>>
>>
>>
>
> p = ["".join(s) for s in permute('abcdefg')]

This fails to work too. I'm trying to call permute func from another func,
python gives me a TypeError as follows:

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

def main(stringList):
    for string in stringList:
        permList = list(permute(string))
        l = ["".join(s) for s in permList]

>>> l = ['abc','abd','bcd']
>>> main(l)
TypeError: can only concatenate tuple (not "list") to tuple



>
> --
> James Stroud
> UCLA-DOE Institute for Genomics and Proteomics
> Box 951570
> Los Angeles, CA 90095
>
> http://www.jamesstroud.com/
> --
> http://mail.python.org/mailman/listinfo/python-list
>




More information about the Python-list mailing list