我正在尝试借助文本文档来排列从最短到最长的字谜列表。我不确定该怎么做。我试过安排字谜,但似乎无法正常工作。
# function that sorts letters in a string in ascending order
def signature ( s ):
t = sorted( s )
return ''.join(t)
# function that builds a dictionary whose keys are the signatures of the
# words from words.txt and their values are the different anagrams for the
# corresponding keys
#
def all_anagrams( filename ):
# define a dictionary
d = { }
for w in open(filename):
t = signature( w.strip().lower())
if t not in d:
d[t] = [ w.strip().lower() ]
else:
d[t].append( w.strip().lower() )
return d
#function to print contents of dictionary d
#that is, the list of anagrams previously stored in it
def isAnagram(str1, str2):
str1_list = list(str1)
str1_list.sort()
str2_list = list(str2)
str2_list.sort()
return (str1_list == str2_list)
#
# Let's test our solution
#
anagrams = all_anagrams("words.txt")
print_anagrams( anagrams)
#
['aah', 'aha']['aahed', 'ahead']['aal', 'ala']
This should be the output
#