An anagram is a word, a phrase, or a sentence formed from another by rearranging its letters. An example of this is "angel", which is an anagram of "glean".
Write a function that receives an array of words, and returns the total number of distinct pairs of anagramic words inside it.
Some examples:
There are 2 anagrams in the array
["dell", "ledl", "abc", "cba"]
There are 7 anagrams in the array
["dell", "ledl", "abc", "cba", "bca", "bac"]
My code is usually not optimal, and I would like to improve my coding practices, and coding sense which is why I try to put up for review all nontrivial code I write.
My Code
from collections import Counter
import math
def choose(n, k): #Each distinct anagram pair is a selection from the set of all words that have the same count.
f = math.factorial
return (f(n)//(f(n-k)*f(k)))
def anagram_counter(words):
words = list(set(words)) #Suppress duplicates.
unique = set() #Set of unique words.
count = {} #Dictionary that stores the count for each word.
unique = set()
for word in words:
#The current word is not an anagram of any word already in the set.
wordID = Counter(word)
if not unique or all((wordID != count[distinct][1] for distinct in unique)):
unique.add(word)
count[word] = [1,wordID] #A tuple containing number of anagrams of a word and its `wordID`.
else: #If the current word is an anagram of a word already in the set.
for distinct in list(unique):
if count[distinct][1] == wordID: #If the word is an anagram of a preexisting word.
count[distinct][0] += 1 #Increment the counter.
break
return 0 if count == {} else sum((choose(itm[0], 2) for itm in count.values() if itm[0] > 1))