Given a set of words, we need to find the anagram words and display each category alone using the best algorithm.
input:
man car kile arc none like
<
A Python version for giggles:
from collections import defaultdict
res = defaultdict(list)
L = "car, acr, bat, tab, get, cat".split(", ")
for w in L:
res["".join(sorted(w))].append(w)
print(res.values())
python code:
line = "man car kile arc none like"
hmap = {}
for w in line.split():
ws = ''.join(sorted(w))
try:
hmap[ws].append(w)
except KeyError:
hmap[ws] = [w]
for i in hmap:
print hmap[i]
output:
['car', 'arc']
['kile', 'like']
['none']
['man']