How to define a function that returns a list of all words in a file that are anagrams of a input string in python

1.1k Views Asked by At

I need to define a function called find_anagrams(str) which returns a lists of all words in dictionary.txt that are anagrams of the input string. I already have a code which returns words from a list that are anagrams of a string.

def find_anagrams_in_word_list(str1,str_list):
    anagrams = []
    for word in str_list:
        if len(word) == len(str1):
            if (anagram(str1,word)):
                anagrams.append(word)
                print(word)

and a code which opens the dictionary file

def get_dictionary_word_list():
    with open('dictionary.txt') as f:
        return f.read().split

How do i send the input string and the word list (get_dictionary_word_list) to find_anagrams_in_word_list to get the result?

so if the str was 'advar' i would like it to return 'varad', 'davar', 'ravad' (assuming they are in the word file)

2

There are 2 best solutions below

5
On BEST ANSWER

As in your previous question if sorted(str1) == sorted(str2) returns True you have an anagram. There is very little difference using a file, all you need is to split file into individual words, strip any whitespace and use a list comprehension again to compare:

def anagram(str1,str2):
    return sorted(str1) ==  sorted(str2)


def find_anagrams(s,f):
    with open(f) as f:
        return [word.rstrip() for word in f if anagram(word.rstrip(),s)]

Or using your own code:

def get_dictionary_word_list():
    with open('dictionary.txt') as f:
        return f.read().split() # need parens to call the split method

def anagram(str1,str2):
    return sorted(str1) ==  sorted(str2)


def find_anagrams(s):
    return [word for word in get_dictionary_word_list() if anagram(word,s)]

If you are using split you don't need rstrip

0
On

I would make a function called isAnagram to check if a particular word itself is an anagram. The parameters can be the original word, and the word you are testing.

from collections import Counter
def isAnagram(original, test):
    return Counter(original) == Counter(test)

Testing this function:

>>> isAnagram('basket', 'skabet')
True

Now we can use the above function while reading (assuming one word per line in dictionary.txt). The parameters can be the path to the file, and the word you want to find anagrams of.

def getAnagramList(filename, original):
    with open(filename) as f:
        return [word for word in f if isAnagram(original, word)]

With a test file with a few anagrams of 'basket'

>>> getAnagramList('dictionary.txt', 'basket')
['skabet', 'tebask', 'askbet']