config

view python/anagram.py @ 224:57677a2bf772

remove umask
author Jeff Hammel <jhammel@mozilla.com>
date Wed May 16 08:58:47 2012 -0700 (2 days ago)
parents 099a3bfa2852
children
line source
1 #!/usr/bin/env python
3 import os
5 dictionary = []
7 def read_dictionary(f):
8 for name in f.readlines():
9 name = name.strip('\n')
10 word = ''.join(name.split()).lower()
11 dictionary.append(word)
13 def is_in(string1, string2):
15 string2 = list(string2)
17 try:
18 for i in string1:
19 string2.remove(i)
20 except ValueError:
21 return None
23 return ''.join(string2)
25 def anagramize(theword, wordlist, level=0):
27 if 0:
28 print '%s%s : %s' % ('-' * level, theword, wordlist)
30 anagrams = []
32 # start the search with a new word
33 for index in range(len(wordlist)):
34 word = wordlist[index]
35 subword = is_in(word, theword)
36 if subword == '':
37 anagrams.append(word)
38 continue
40 if subword is None:
41 continue
44 sublist = [ i for i in wordlist[index:]
45 if is_in(i, subword) is not None ]
46 subgram = anagramize(subword, sublist, level+1)
48 if subgram is not None:
49 anagrams += [ ' '.join((word, i)) for i in subgram ]
51 if 0:
52 print '%s%s returning %s' % ('-' * level, theword, anagrams)
54 if anagrams:
55 return anagrams
56 return None
58 if __name__ == '__main__':
59 import sys
60 from optparse import OptionParser
62 parser = OptionParser()
63 parser.add_option("-f", dest="filename", help="dictionary to read",
64 default='')
65 (options, args) = parser.parse_args()
67 if not os.path.exists(options.filename):
69 dicts = [ '/home/jhammel/docs/dict.txt',
70 '/usr/share/dict/cracklib-small',
71 '/usr/share/dict/american-english' ]
73 for i in dicts:
74 if os.path.exists(i):
75 options.filename = i
76 break
77 else:
78 print 'Dictionary not found'
79 parser.print_help()
80 sys.exit(1)
82 if not args:
83 print 'please provide an anagram'
84 sys.exit(0)
86 f = file(options.filename, 'r')
87 read_dictionary(f)
89 # XXX could cleanup
90 anagram = ' '.join(args)
91 anagram = ''.join(anagram.split()).lower()
93 # don't use letter names
94 dictionary = [ i for i in dictionary if (len(i) > 1) or i in 'ai' ]
96 wordlist = [ i for i in dictionary
97 if i and is_in(i, anagram) is not None ]
99 anagrams = anagramize(anagram, wordlist)
101 if anagrams:
102 print '\n'.join(anagrams)