comparison python/anagram.py @ 896:83618049c2ff

py3
author Jeff Hammel <k0scist@gmail.com>
date Fri, 11 Feb 2022 09:33:38 -0800
parents 4096771c8b9f
children
comparison
equal deleted inserted replaced
895:8d3df8c0c730 896:83618049c2ff
23 return ''.join(string2) 23 return ''.join(string2)
24 24
25 def anagramize(theword, wordlist, level=0): 25 def anagramize(theword, wordlist, level=0):
26 26
27 if 0: 27 if 0:
28 print '%s%s : %s' % ('-' * level, theword, wordlist) 28 print('%s%s : %s' % ('-' * level, theword, wordlist))
29 29
30 anagrams = [] 30 anagrams = []
31 31
32 # start the search with a new word 32 # start the search with a new word
33 for index in range(len(wordlist)): 33 for index in range(len(wordlist)):
47 47
48 if subgram is not None: 48 if subgram is not None:
49 anagrams += [ ' '.join((word, i)) for i in subgram ] 49 anagrams += [ ' '.join((word, i)) for i in subgram ]
50 50
51 if 0: 51 if 0:
52 print '%s%s returning %s' % ('-' * level, theword, anagrams) 52 print('%s%s returning %s' % ('-' * level, theword, anagrams))
53 53
54 if anagrams: 54 if anagrams:
55 return anagrams 55 return anagrams
56 return None 56 return None
57 57
58 if __name__ == '__main__': 58 if __name__ == '__main__':
59 import sys 59 import sys
60 from optparse import OptionParser 60 from optparse import OptionParser
61 61
62 parser = OptionParser() 62 parser = OptionParser()
73 for i in dicts: 73 for i in dicts:
74 if os.path.exists(i): 74 if os.path.exists(i):
75 options.filename = i 75 options.filename = i
76 break 76 break
77 else: 77 else:
78 print 'Dictionary not found' 78 print('Dictionary not found')
79 parser.print_help() 79 parser.print_help()
80 sys.exit(1) 80 sys.exit(1)
81 81
82 if not args: 82 if not args:
83 print 'please provide an anagram' 83 print('please provide an anagram')
84 sys.exit(0) 84 sys.exit(0)
85 85
86 f = file(options.filename, 'r') 86 with open(options.filename, 'r') as f:
87 read_dictionary(f) 87 read_dictionary(f)
88 88
89 # XXX could cleanup 89 # XXX could cleanup
90 anagram = ' '.join(args) 90 anagram = ' '.join(args)
91 anagram = ''.join(anagram.split()).lower() 91 anagram = ''.join(anagram.split()).lower()
92 92
93 # don't use letter names 93 # don't use letter names
94 dictionary = [ i for i in dictionary if (len(i) > 1) or i in 'ai' ] 94 dictionary = [ i for i in dictionary if (len(i) > 1) or i in 'ai' ]
95 95
96 wordlist = [ i for i in dictionary 96 wordlist = [ i for i in dictionary
97 if i and is_in(i, anagram) is not None ] 97 if i and is_in(i, anagram) is not None ]
98 98
99 anagrams = anagramize(anagram, wordlist) 99 anagrams = anagramize(anagram, wordlist)
100 100
101 if anagrams: 101 if anagrams:
102 print '\n'.join(anagrams) 102 print('\n'.join(anagrams))