Using Python, find anagrams for a list of words

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

    Most of previous answers are correct, here is another way to compare two strings. The main benefit of using this strategy versus sort is space/time complexity which is n log of n.

    1.Check the length of string

    2.Build frequency Dictionary and compare if they both match then we have successfully identified anagram words

    def char_frequency(word):
        frequency  = {}
        for char in word:
            #if character  is in frequency then increment the value
            if char in frequency:
                frequency[char] += 1
            #else add character and set it to 1
            else:
                frequency[char] = 1
        return frequency 
    
    
    a_word ='google'
    b_word ='ooggle'
    #check length of the words 
    if (len(a_word) != len(b_word)):
       print ("not anagram")
    else:
        #here we check the frequecy to see if we get the same
        if ( char_frequency(a_word) == char_frequency(b_word)):
            print("found anagram")
        else:
            print("no anagram")
    

提交回复
热议问题