comparison python/anagram.py @ 0:f3ab51c79813

adding configuration from https://svn.openplans.org/svn/config_jhammel/
author k0s <k0scist@gmail.com>
date Thu, 15 Oct 2009 11:41:26 -0400
parents
children 099a3bfa2852
comparison
equal deleted inserted replaced
-1:000000000000 0:f3ab51c79813
1 #!/usr/bin/env python
2
3 import os
4
5 dictionary = []
6
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)
12
13 def is_in(string1, string2):
14
15 string2 = list(string2)
16
17 try:
18 for i in string1:
19 string2.remove(i)
20 except ValueError:
21 return None
22
23 return ''.join(string2)
24
25 def anagramize(theword, wordlist, level=0):
26
27 if 0:
28 print '%s%s : %s' % ('-' * level, theword, wordlist)
29
30 anagrams = []
31
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
39
40 if subword is None:
41 continue
42
43
44 sublist = [ i for i in wordlist[index:]
45 if is_in(i, subword) is not None ]
46 subgram = anagramize(subword, sublist, level+1)
47
48 # import pdb; pdb.set_trace()
49 if subgram is not None:
50 anagrams += [ ' '.join((word, i)) for i in subgram ]
51
52 if 0:
53 print '%s%s returning %s' % ('-' * level, theword, anagrams)
54
55 if anagrams:
56 return anagrams
57 return None
58
59 if __name__ == '__main__':
60 import sys
61 from optparse import OptionParser
62
63 parser = OptionParser()
64 parser.add_option("-f", dest="filename", help="dictionary to read",
65 default='')
66 (options, args) = parser.parse_args()
67
68 if not os.path.exists(options.filename):
69
70 dicts = [ '/home/jhammel/docs/dict.txt',
71 '/usr/share/dict/cracklib-small',
72 '/usr/share/dict/american-english' ]
73
74 for i in dicts:
75 if os.path.exists(i):
76 options.filename = i
77 break
78 else:
79 print 'Dictionary not found'
80 parser.print_help()
81 sys.exit(1)
82
83 if not args:
84 print 'please provide an anagram'
85 sys.exit(0)
86
87 f = file(options.filename, 'r')
88 read_dictionary(f)
89
90 anagram = ' '.join(args)
91
92 print anagram
93 print '-' * len(anagram)
94
95 anagram = ''.join(anagram.split()).lower()
96
97 # don't use letter names
98 dictionary = [ i for i in dictionary if (len(i) > 1) or i in 'ai' ]
99
100 wordlist = [ i for i in dictionary
101 if i and is_in(i, anagram) is not None ]
102
103 anagrams = anagramize(anagram, wordlist)
104
105 print '\n'.join(anagrams)