Trying to come up with python anagram function

后端 未结 7 2016
梦谈多话
梦谈多话 2021-01-23 14:02

What I\'m trying to do is if I have a list like:

[\"lime\", \"mile\", \"liem\", \"tag\", \"gat\", \"goat\", \"math\"]

I want to write a functio

7条回答
  •  暖寄归人
    2021-01-23 14:32

    An algorithm to check if two words are anagrams in python.

    1) Take two words: e.g.

    ("mile", "lime") ("tiles", "miles")

    2) Make a string array/list:

    (['m', 'i', 'l', 'e'], ['l', 'i', 'm', 'e']) (['t', 'i', 'l','e', 's'], ['m', 'i', 'l', 'e', 's'])

    3) Sort arrays

    (['e', 'i', 'l', 'm'], ['e', 'i', 'l', 'm']) (['e', 'i', 'l','s', 't'], ['e', 'i', 'l', 'm', 's'])

    4)Check if first_array[i] == second_array[i] for 0<=i<=len(first_array)||second_array

    5) Conclusion. If 4) is held, return true, else false.

    from itertools import combinations
    
    def anagram(w1,w2):
        list1 = list(w1)
        list2 = list(w2)
    
        list1.sort()
        list2.sort()
    
        idx = 0
        is_anagram = True
    
        while idx < len(w1) and is_anagram:
            if list1[idx]== list2[idx]:
                idx += 1
            else:
                is_anagram = False
        return is_anagram
    
    
    lst_words = ["lime", "mile", "liem", "tag", "gat", "goat", "math"]
    lst_anagrams = set()
    for i in combinations(lst_words, 2):
        if anagram(*i):
            lst_anagrams |= set(i) 
    
    print list(lst_anagrams)
    

提交回复
热议问题