fork download
  1. def group_anagrams(words):
  2. groups = {}
  3.  
  4. for w in words:
  5. key = "".join(sorted(w)) # сортируем буквы
  6.  
  7. if key not in groups:
  8. groups[key] = []
  9.  
  10. groups[key].append(w)
  11.  
  12. return list(groups.values())
  13.  
  14. print(group_anagrams(["eat","tea","tan","ate","nat","bat"]))
Success #stdin #stdout 0.02s 7172KB
stdin
Standard input is empty
stdout
[['tan', 'nat'], ['bat'], ['eat', 'tea', 'ate']]