calvin2011
calvin2011

Reputation: 387

Comparing a string with a list of strings to find anagrams in Python

I am trying to work out how to compare a string (str1) with a list of strings (str_list), and then return a list of all the strings in str_list that are anagrams of str1.

I have previously defined a function to compare two strings and print True if they are anagrams of each other, and False if not.

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

I have attempted to start to define the next function but I'm struggling to return the list of strings that are anagrams.

def find_anagrams_in_word_list(str1, str_list):
     str_list = [] #assumed an empty list has to be made first
     str_list = input
     if sorted(str1) in sorted(str_list):
           #return strings that are anagrams

Not sure if this is how I'm meant to do it as I'm still a beginner, so any pointers would be very helpful!

Thanks.

Upvotes: 0

Views: 1211

Answers (2)

Kasravnd
Kasravnd

Reputation: 107347

You can use a generators for that , Also note that the result of sorted function is a list and you need to convert it to string with ''.join() and then compare :

def find_anagrams_in_word_list(str1, str_list):
     return [ i for i in str_list if ''.join(sorted(str1)) == ''.join(sorted(i))]

Demo :

>>> l =['abcd', 'msnd']
>>> find_anagrams_in_word_list('cba',l)
['abcd']

Upvotes: 1

Cory Kramer
Cory Kramer

Reputation: 118021

The faster way to do this would be to use collections.Counter

from collections import Counter
def isAnagram(str1, str2):
    return Counter(str1) == Counter(str2)

def find_anagrams_in_word_list(str1, str_list):
    return [word for word in str_list if isAnagram(str1, word)]

Note that your isAnagram will not behave as you expect because you only print the value, you do not return it. For you to be able to use your isAnagram function, as I did in my above list comprehension for example, you'd have to do one of the following.

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

Or more concisely

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

Upvotes: 2

Related Questions