I have two versions of logic for finding out the anagrams in a list of words:
- The first one uses Python's collections module and uses
Counter
:
def anagram_checker(cls, word=None, words=[]):
anagrams = []
if len(words) == 0: # if the second arg list is empty then there is nothing to check
return anagrams
else:
counter_word = Counter(word)
for given_word in words:
if given_word != word: # Cannot be same as the word in question
if Counter(given_word) == counter_word:
anagrams.append(given_word)
return anagrams
- The second one has same functionality but using the sorted builtin function.
def anagram_checker(cls, word=None, words=[]):
anagrams = []
if len(words) == 0: # if the second arg list is empty then there is nothing to check
return anagrams
else:
counter_word = list(sorted(word))
for given_word in words:
if given_word != word: # Cannot be same as the word in question
if list(sorted(given_word)) == counter_word:
anagrams.append(given_word)
return anagrams
Which has better time complexity . I mean is comparing Python Counter objects has better complexity or comparing sorted lists has better time complexity?
If i am not wrong comparing lists have a complexity of O(n) right . What is the complexity of comparing two Counter objects.
I have searched various documentation but have not found any satisfactory answer for the same.
Kindly help.