C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Sorted_line: This method alphabetizes the characters in a string. It uses a list comprehension to get a list, then sorts it and joins it.
SortAnagram: This method returns a list of anagrams for a word. It sorts again and splits the result string from the dictionary.
Python program that finds anagrams
def build_dict(path):
# Load in word file and sort each line.
alpha = {}
f = open(path, "r")
for line in f.readlines():
line = line.strip()
key = sorted_line(line)
# Add each line to a dictionary based on its sorted key.
if key in alpha:
v = alpha.get(key) + "," + line
alpha[key] = v
else:
alpha[key] = line
return alpha
def sorted_line(line):
# Sort the chars in this line and return a string.
chars = [c for c in line]
chars.sort()
return "".join(chars)
def anagram(alpha, line):
# Return a list of anagrams from the dictionary.
# ... Use a sorted string as the key.
key = sorted_line(line)
values = alpha.get(key, "NONE")
return values.split(",")
# Load our dictionary and use it.
alpha = build_dict(r"C:\enable1.txt")
results = anagram(alpha, "spot")
print("Anagrams for [spot]")
print(results)
Output
Anagrams for [spot]
['opts', 'post', 'pots', 'spot', 'stop', 'tops']
Tip: For top performance, a directed acyclic graph is used to find anagrams. Matches can be found by a simple tree traversal.
Word list: The word list used in the program is available on the Internet. I recommend a Google search.