Hello, Asrarahmed
> -----Original Message-----
> Date: Mon, 27 Nov 2006 12:06:54 +0000
> From: "Asrarahmed Kadri" <[EMAIL PROTECTED]>
> Subject: [Tutor] How to generate permutations of a given string
> To: tutor-python <[email protected]>
> Message-ID:
> <[EMAIL PROTECTED]>
> Content-Type: text/plain; charset="iso-8859-1"
>
> Hello folks,
>
>
> Can someone help me with a simple algorithm to generate permutations
of a
> given string:
>
> Input string:---->> 'abc'
>
> Output:------->> ['abc','acb','bac','bca','cab','cba']
>
> Thanks.
> Regards,
> Asrarahmed Kadri
> -
> To HIM you shall return.
I'm not sure these qualify as "simple", but they work. This was one of
my very first projects in Python, so it may be more complicated than
necessary.
##########
def permute (word):
"""
Accepts a string.
Returns a list of all permutations of the string using all
characters.
"""
retList=[]
if len(word) == 1:
# There is only one possible permutation
retList.append(word)
else:
# Return a list of all permutations using all characters
for pos in range(len(word)):
# Get the permutations of the rest of the word
permuteList=permute2(word[0:pos]+word[pos+1:len(word)])
# Now, tack the first char onto each word in the list
# and add it to the output
for item in permuteList:
retList.append(word[pos]+item)
return retList
##########
Regards,
Barry
[EMAIL PROTECTED]
541-302-1107
________________________
We who cut mere stones must always be envisioning cathedrals.
-Quarry worker's creed
_______________________________________________
Tutor maillist - [email protected]
http://mail.python.org/mailman/listinfo/tutor