Trying to come up with python anagram function

后端 未结 7 2010
梦谈多话
梦谈多话 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:33

    That's a decent start (though it would be clearer if you named the variables something like 'wordlist', 'word' (or even 'w'), and 'char' or 'c'...). But a couple issues:

    1: for each word ('i'), you need to compare the other words, hoping to find at least one that is an anagram of i.

    2: you need to see if any character fails to be found.

    You could start like this:

    output = []     
    for w1 in wordlist:
        for w2 in wordList:
            if w1==w2: continue  # don't compare to self
            match = True  # hope for the best
            for c in w1:
                if c not in w2: 
                    match = False
                    break
            if (match):
               output.append(w1)
               break
    

    That's close, but isn't actually enough, because to be a true anagram you have to have the same number of occurrences of each letter, not just the same set of distinct letters (consider 'mail' vs 'milla' or 'mailmailmail').

    One way to do that would be to make a copy of w2, and then as you go through the characters of w1, remove the letter in that copy that matches against each letter of w1. That way it can't match twice. And, you'd need to make sure the copy has become empty when you 're done with the 'c' loop.

    There are many other ways; some clever ones involve "collection" types such as set and multiset. And as Captain Wise suggested, sorting the characters in each word alphabetically lets you just compare them, instead of looping through characters one at a time.

    Hope that helps.

    -s

    0 讨论(0)
提交回复
热议问题