Back to SDS/2 Parametric Scripts

 

# Posted on http://www.thescripts.com/forum/forum152.html

# Returns a list (Python 2.3) or set (Python 2.4) with all

# possible letter combinations of the argument string

 

# Python 2.3

def anagrams(s):

    if s == "":

        return [s]

    else:

        ans = []

        for an in anagrams(s[1:]):

            for pos in range(len(an)+1):

                ans.append(an[:pos]+s[0]+an[pos:])

                u={}

        for i in ans:

            u[i]=1

        return u.keys()

 

# Python 2.4

def anagrams(s):

    if s == "":

        return [s]

    else:

        ans = set()

        for an in anagrams(s[1:]):

            for pos in range(len(an)+1):

                ans.add(an[:pos]+s[0]+an[pos:])

        return ans

 

“””

>>> anagrams('tor')

['tro', 'tor', 'rto', 'otr', 'rot', 'ort']

>>> anagrams('oot')

['oot', 'too', 'oto']

>>> anagrams('ebre')

['bere', 'eebr', 'rebe', 'ereb', 'eerb', 'eber', 'beer', 'erbe', 'rbee', 'reeb', 'bree', 'ebre']

>>>