pythonpython-3.xlistanagram

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
    else:
        return False

Any help is appreciated


Solution

  • 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)