Using Python, find anagrams for a list of words

前端 未结 22 885
失恋的感觉
失恋的感觉 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条回答
  •  Happy的楠姐
    2020-12-13 01:28

    I'm using a dictionary to store each character of string one by one. Then iterate through second string and find the character in the dictionary, if it's present decrease the count of the corresponding key from dictionary.

    class Anagram:
    
        dict = {}
    
        def __init__(self):
            Anagram.dict = {}
    
        def is_anagram(self,s1, s2):
            print '***** starting *****'
    
            print '***** convert input strings to lowercase'
            s1 = s1.lower()
            s2 = s2.lower()
    
            for i in s1:
               if i not in Anagram.dict:
                  Anagram.dict[i] = 1
               else:
                  Anagram.dict[i] += 1
    
            print Anagram.dict
    
            for i in s2:
               if i not in Anagram.dict:
                  return false
               else:
                  Anagram.dict[i] -= 1
    
            print Anagram.dict
    
           for i in Anagram.dict.keys():
              if Anagram.dict.get(i) == 0:
                  del Anagram.dict[i]
    
           if len(Anagram.dict) == 0:
             print Anagram.dict
             return True
           else:
             return False
    

提交回复
热议问题