defining a function which calls another function for a variety of strings python

121 views Asked by At

I have a code which finds anagrams of a string in a dictionary file. I want to create a function which tests a variety of strings called test_find_anagrams(). It should test at least 6 different strings.

This is the code i have which tests a single string in a file.

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

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

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

So far i have this code to test different strings, It works on the first string in the list but doesnt return anything for any string after. What else do i need to put in the code for it to work?

def test_find_anagrams():
    stringlist = [('aces'), ('sidebar'), ('adverb'), ('fuels'), ('hardset'), ('praised')]
    for str1 in stringlist:
        return [word for word in get_dictionary_word_list() if anagram(word,str1)]
1

There are 1 answers

6
Steven Rumbalski On BEST ANSWER

It only "works on the first string in the list" because you return from inside the loop. Keep track of your result outside of the loop.

def test_find_anagrams():
    stringlist = [('aces'), ('sidebar'), ('adverb'), ('fuels'), ('hardset'), ('praised')]
    result = []
    for str1 in stringlist:
        result.extend(word for word in get_dictionary_word_list() if anagram(word,str1))
    return result