Using Python, find anagrams for a list of words

前端 未结 22 913
失恋的感觉
失恋的感觉 2020-12-13 01:11

If I have a list of strings for example:

[\"car\", \"tree\", \"boy\", \"girl\", \"arc\"...]

What should I do in order to find anagrams in t

22条回答
  •  忘掉有多难
    2020-12-13 01:40

    >>> words = ["car", "race", "rac", "ecar", "me", "em"]
    >>> anagrams = {}
    ... for word in words:
    ...     reverse_word=word[::-1]
    ...     if reverse_word in words:
    ...         anagrams[word] = (words.pop(words.index(reverse_word)))
    >>> anagrams
    20: {'car': 'rac', 'me': 'em', 'race': 'ecar'}
    

    Logic:

    1. Start from first word and reverse the word.
    2. Check the reversed word is present in the list.
    3. If present, find the index and pop the item and store it in the dictionary, word as key and reversed word as value.

提交回复
热议问题