![]() ![]() import sysĪlpha_count_dict = dict(zip('abcdefghijklmnopqrstuvwxyz',*26)) You can refer to this SO post: Comparing anagrams using prime numbers, and here is a sample python implementation.ġ.create a dictionary of alphabets/characters with initial count as 0.Ģ.keep count of all the alphabets in the word and increment the count in the above alphabet dict.ģ.create alphabet count dict and return the tuple of the values of alphabet dict.ġ.create a dictionary with alphabet count tuple as key and the count of the number of occurences against it.Ģ.iterate over the above dict and if the value > 1, add the value to the anagram count. This is a more advanced solution, that relies on the "multiplicative uniqueness" of prime numbers. Note that constructing Counter is O(l), while sorting each word is O(n*log(l)) where l is the length of the word. "bac", "silenced", "licensed", "declines") Histogram = tuple(Counter(word).items()) # build a hashable histogram Here is the code: from collections import Counter, defaultdict For each word build it's histogram and add it to the list that corresponds to this histogram.Build a dictionary where keys would be histograms and values would be lists of words that have this histogram.This is a perfect use case for collections.Counter data structure ( see docs). This is basically a histogram of letters count of each word. There are multiple solutions to this problem:įirst, let's consider what defines an anagram: two words are anagrams of each other if they consist of the same set of letters and each letter appears exactly the same number or time in both words.
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |