A function that uses a string and string list and returns all the words in the list that are anagrams of the string

2.2k views Asked by At

I want to define a function find_anagrams_in_word_list(str,str_list) where the parameters should be a string and a list of strings. The value returned should be a list of all the strings in the str_list that are values of str.

I have a simple code that allows you to see if a word is an anagram of a another

def anagram(str1,str2):
    str1 = sorted(str1)
    str2 = sorted(str2)
    if str1 == str2:
        print("True")
    else:
        print("False")

But i can't seem to understand how to use this for a list.

edit

def anagram(str1,str2):
    str1 = sorted(str1)
    str2 = sorted(str2)
if str1 == str2:
    print("True")
else:
    print("False")

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

I have gotten this far in creating this code but instead of printing the words if they are anagrams of 'str1' it prints '[]' which i think means that the words in str_list are not being appended to 'anagrams'

I want a output like this

find_anagrams_in_word_list("rat", "[art,tar,gar,jay]")

'art' 'tar'

as they are anagrams of rat.

3

There are 3 answers

0
Padraic Cunningham On BEST ANSWER
def anagram(str1,str2):
    str1 = sorted(str1)
    str2 = sorted(str2)
    return str1 == str2 # will be True or False no need for if checks


def find_anagrams_in_word_list(str1,str_list):
    return " ".join([word for word in str_list if anagram(word,str1)]) 

print (find_anagrams_in_word_list("rat", ["art","tar","gar","jay"]))
art tar

if anagram(word,str1) checks each or in the list against the passed in str1, if anagram returns True then we keep that word, finally " ".join outputs all the words in the list as a single string.

3
aaveg On
def anagram(str1,str2):
   str1 = sorted(str1)
   str2 = sorted(str2)
   if str1 == str2:
      return True
   else:
      return False

print [i for i in str_list if anagram(str,i)]

Here, str is the string to be matched and str_list is the list of all the strings

EDIT:

To turn this into a fuction, try this:

def anagram(str1,str_list):
    str1 = sorted(str1)
    temp_list=[i for i in str_list if sorted(i)==str1]
    return temp_list
0
micgeronimo On
def anagram(my_str,my_list):
    result_list = []
    for item in my_list:
        if item == my_str:
            result_list.append(item)
    return result_list

Then you have to assign variables and pass them to your function like this

somestr = 's'
somelist = ['s','not s','m','etc','s']
my_anagram = anagram(somestr,somelist)

So you will get variable my_anagram which contains list of matched elements