Using Python, find anagrams for a list of words

前端 未结 22 868
失恋的感觉
失恋的感觉 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:40
    >>> words = ["car", "race", "rac", "ecar", "me", "em"]
    >>> anagrams = {}
    ... for word in words:
    ...     reverse_word=word[::-1]
    ...     if reverse_word in words:
    ...         anagrams[word] = (words.pop(words.index(reverse_word)))
    >>> anagrams
    20: {'car': 'rac', 'me': 'em', 'race': 'ecar'}
    

    Logic:

    1. Start from first word and reverse the word.
    2. Check the reversed word is present in the list.
    3. If present, find the index and pop the item and store it in the dictionary, word as key and reversed word as value.
    0 讨论(0)
  • 2020-12-13 01:41
    def all_anagrams(words: [str]) -> [str]:
        word_dict = {}
        for word in words:
            sorted_word  = "".join(sorted(word))
            if sorted_word in word_dict:
                word_dict[sorted_word].append(word)
            else:
                word_dict[sorted_word] = [word]
        return list(word_dict.values())  
    
    0 讨论(0)
  • 2020-12-13 01:43

    You convert each of the character in a word into a number (by ord() function), add them up for the word. If two words have the same sum, then they are anagrams. Then filter for the sums that occur more than twice in the list.

    def sumLet(w):
        return sum([ord(c) for c in w])
    
    def find_anagrams(l):
        num_l = map(sumLet,l)
        return [l[i] for i,num in enumerate(num_l) if num_l.count(num) > 1]
    
    0 讨论(0)
  • 2020-12-13 01:43

    If you want a solution in java,

    public List<String> findAnagrams(List<String> dictionary) {
    
        // TODO do null check and other basic validations.
        Map<String, List<String>> wordMap = new HashMap<String, List<String>>();
    
        for(String word : dictionary) {
    
            // ignore if word is null
            char[] tempWord = word.tocharArray();
            Arrays.sort(tempWord);
            String newWord = new String(tempWord);
    
            if(wordMap.containsKey(newWord)) {
                wordMap.put(newWord, wordMap.get(word).add(word));
            } else {
                wordMap.put(newWord, new ArrayList<>() {word});
            }
    
        }
    
        List<String> anagrams = new ArrayList<>();
    
        for(String key : wordMap.keySet()) {
    
            if(wordMap.get(key).size() > 1) {
                anagrams.addAll(wordMap.get(key));
            }
    
        }
    
        return anagrams;
    }
    
    0 讨论(0)
提交回复
热议问题