python - Finding anagrams contained in a given string -


i'm trying write program accepts string , groups anagrams of string in list of lists, sorted lexicographically.

for example, following string:

eat tea tan ate nat bat 

should produce following output(order of lines important):

ate eat tea bat nat tan 

the program have written:

from collections import defaultdict  def get_anagrams(source): d = defaultdict(list) word in source:     key = "".join(sorted(word))     d[key].append(word) return d  def print_anagrams(my_string): word_source = my_string.split(" ") d = get_anagrams(word_source) key, anagrams in d.items():     print(" ".join(sorted(anagrams)))  print_anagrams("eat tea tan ate nat bat") 

this program produces correct anagrams, each time run program order of lines compared expected output change.

so get

nat tan ate eat tea bat 

and other times correct output

ate eat tea bat nat tan 

can please point out i'm doing wrong?

the order of dictionary keys random design.

if want print anagrams in order of occurrence in original text, use ordereddict stores keys in same order inserted them:

from collections import ordereddict  def get_anagrams(source):     d = ordereddict()     word in source:         key = "".join(sorted(word))         if key not in d:             d[key] = []         d[key].append(word)     return d  def print_anagrams(my_string):     word_source = my_string.split(" ")     d = get_anagrams(word_source)     key, anagrams in d.items():         print(" ".join(sorted(anagrams)))  print_anagrams("eat tea tan ate nat bat") 

output:

ate eat tea nat tan bat 

Comments

Popular posts from this blog

html - Outlook 2010 Anchor (url/address/link) -

javascript - Why does running this loop 9 times take 100x longer than running it 8 times? -

Getting gateway time-out Rails app with Nginx + Puma running on Digital Ocean -