producing all the anagrams from a string python

Viewed 32430

I was thinking about this problem today, and I came with the following pseudocode (Python 3.2) :

def anagrams( string ):

    for c in string:
      anagram = c + anagram( string - {c} ) # remove the char from its position in the string
      print(anagram)

    return

def main():

    word = "abcd"
    anagrams( word )

    return

However, I'd like to know a pythonic way to do this operation: anagram = c + anagram( string - {c} )

How could I remove that char from the string? so for example:

"abc" -> 'a' + "bc" -> 'a' + 'b' + "c" -> 'a' + 'b' + 'c' = 'abc'
             + "cb" -> 'a' + 'c' + "b" -> 'a' + 'c' + 'b' = 'acb'
      -> 'b' + "ac" -> 'b' + 'a' + "c" -> 'b' + 'a' + 'c' = 'bac'
             + "ca" -> 'b' + 'c' + "a" -> 'b' + 'c' + 'a' = 'bca'
      -> 'c' + "ba" -> 'c' + 'b' + "a" -> 'c' + 'b' + 'a' = 'cba'
             + "ab" -> 'c' + 'a' + "b" -> 'c' + 'a' + 'b' = 'cab'

Thanks

5 Answers

Here's some of the suggestions wrapped up to make a new script, called anagram

$ anagram hit
hit
hti
iht
ith
thi
tih

anagram

#!/usr/bin/env python3
import argparse
import itertools
import sys

parser = argparse.ArgumentParser()
parser.add_argument("word", help="A word to generate anagrams for.")
args = parser.parse_args()

perms = [''.join(perm) for perm in itertools.permutations(args.word)]
for perm in perms:
    print(perm)
Related