[Tutor] How to generate permutations of a given string

Dick Moores rdm at rcblue.com
Tue Nov 28 21:57:51 CET 2006


At 02:49 PM 11/27/2006, John Fouhy wrote:
>On 28/11/06, Carroll, Barry <Barry.Carroll at psc.com> wrote:
> > 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.
>
>This is an alternative approach:
>http://mail.python.org/pipermail/tutor/2005-May/038059.html

However, this is not what someone looking for an anagram algorithm 
would find useful, it seems to me.

Barry Carroll offering does the job, if the last line is revised as 
shown below:

def permute(word):
         """
         By Barry Carrol <Barry.Carroll at psc.com>
         on Tutor list, revised (last line) by me.
         """
         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=permute(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
         return list(set(retList)) # make elements of retList unique

(The line in the code in Barry's post, 
"permuteList=permute2(word[0:pos]+word[pos+1:len(word)])", was 
corrected to "permuteList=permute(word[0:pos]+word[pos+1:len(word)])" 
in an email from him to me.)
(i.e., permute2 changed to permute)

Dick Moores



More information about the Tutor mailing list