[Tutor] More Pythonesque or a more efficient method

Emile van Sebille emile at fenx.com
Wed Oct 8 00:58:12 CEST 2008


Robert Berman wrote:
> Hi,
> 
> The below script which prints anagrams available for any word available 
> within a given database. It does work, but  it is not very fast. I am 
> relatively certain there are more Python friendly coding techniques but 
> I am more concerned with a faster algorithm.

You might consider looking up the permutations only (up to some length 
-- there are a lot of permutations for 8+ letter words :)

#from http://www.daniweb.com/code/snippet459.html

def permutate(seq):
     """permutate a sequence and return a list of the permutations"""
     if not seq:
         return [seq]  # is an empty sequence
     else:
         temp = []
         for k in range(len(seq)):
             part = seq[:k] + seq[k+1:]
             #print k, part  # test
             for m in permutate(part):
                 temp.append(seq[k:k+1] + m)
                 #print m, seq[k:k+1], temp  # test
         return temp

print permutate('myth')

['myth', 'myht', 'mtyh', 'mthy', 'mhyt', 'mhty', 'ymth', 'ymht', 'ytmh', 
'ythm', 'yhmt', 'yhtm', 'tmyh', 'tmhy', 'tymh', 'tyhm', 'thmy', 'thym', 
'hmyt', 'hmty', 'hymt', 'hytm', 'htmy', 'htym']

 >>> print len(permutate('mythsdfw'))
40320
 >>> print len(permutate('mythsdf'))
5040
 >>> print len(permutate('mythsd'))
720
 >>> print len(permutate('myths'))
120
 >>> print len(permutate('myth'))
24
 >>> print len(permutate('myt'))
6

so something like:

print [ xx for xx in permutate('myths') if xx in worddict ]


HTH,

Emile



More information about the Tutor mailing list