Check if any words in two lists are anagrams


I’m trying to write a function where it takes in two lists of any length, and returns True if list_1 has any words that are anagrams in list_2, and false if not.

For example:

words1 = [“dog”, “kitten”]
words2 = [“tiger”, “god”]
return True, as “dog” and “god” are anagrams.

words1 = [“doggy”, “cat”, “tac”]
words2 = [“tiger”, “lion”, “dog”]
return False, as no anagram pair between words1 and words2 exists.

I have a version of the code where I can check specific strings for anagrams, but not sure how to go through two lists and cross check the words:

def anagram_pair_exists(words1, words2):
    if(sorted(words1)== sorted(words2)):
        return True
        return False

Any help is appreciated

Asked By: mlenthusiast



Given you have a check_anagram function that takes two words and gives you a bool result, you can use this:

any(check_anagram(word1, word2) for word1 in list1 for word2 in list2)
Answered By: Ahsanul Haque

I made a version with loops.
Not sure if it is the most efficient with huge lists but it works.

def findAnagram(list1, list2):
    # The lists are preallocated with the right size 
    sortedList1 = [None] * len(list1)
    sortedList2 = [None] * len(list2)
    # Take all the words and sort their letters in alphabetical order (and store them in the new list)
    for index, item in enumerate(list1):
        sortedList1[index] = sorted(item)

    for index, item in enumerate(list2):
        sortedList2[index] = sorted(item)

    # For each item check if it is in the other list
    for item in sortedList1:
        if item in sortedList2:
            return True
    return False

You can try with your lists like this:

words1 = ["dog", "kitten"]
words2 = ["tiger", "godo"]
print(findAnagram(words1, words2))

If you need to check for how many anagrams you have, you could use the count() function.

Instead of the
if item in sortedList2:, use number_count = sortedList2.count(item)
And keep track of the total amount by increasing another variable.

If you need to know which word was an anagram, change the loop so that you return the element at this index in the original (unsorted list).

Answered By: nasmi3
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.