Finding and grouping anagrams by Python

前端 未结 7 1448
無奈伤痛
無奈伤痛 2021-01-20 00:32
input: [\'abc\', \'cab\', \'cafe\', \'face\', \'goo\']
output: [[\'abc\', \'cab\'], [\'cafe\', \'face\'], [\'goo\']]

The problem is simple: it grou

7条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-01-20 00:45

    The readable version:

    from itertools import groupby
    from operator import itemgetter
    
    def norm(w):
      return "".join(sorted(w))
    
    words = ['abc', 'cba', 'gaff', 'ffag', 'aaaa']
    
    words_aug = sorted((norm(word), word) for word in words)
    
    grouped = groupby(words_aug, itemgetter(0))
    
    for _, group in grouped:
      print map(itemgetter(1), group)
    

    The one-liner:

    print list(list(anagrams for _, anagrams in group) for _, group in groupby(sorted(("".join(sorted(word)), word) for word in words), itemgetter(0)))
    

    Prints:

    [['aaaa'], ['abc', 'cba'], ['ffag', 'gaff']]
    

提交回复
热议问题