Using Python, find anagrams for a list of words

前端 未结 22 907
失恋的感觉
失恋的感觉 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:25

    Since you can't import anything, here are two different approaches including the for loop you asked for.

    Approach 1: For Loops and Inbuilt Sorted Function

    word_list = ["percussion", "supersonic", "car", "tree", "boy", "girl", "arc"]
    
    # initialize a list
    anagram_list = []
    for word_1 in word_list: 
        for word_2 in word_list: 
            if word_1 != word_2 and (sorted(word_1)==sorted(word_2)):
                anagram_list.append(word_1)
    print(anagram_list)
    

    Approach 2: Dictionaries

    def freq(word):
        freq_dict = {}
        for char in word:
            freq_dict[char] = freq_dict.get(char, 0) + 1
        return freq_dict
    
    # initialize a list
    anagram_list = []
    for word_1 in word_list: 
        for word_2 in word_list: 
            if word_1 != word_2 and (freq(word_1) == freq(word_2)):
                anagram_list.append(word_1)
    print(anagram_list)
    

    If you want these approaches explained in more detail, here is an article.

提交回复
热议问题