For each number in the array, convert it to a tuple representing its digit frequencies and use this tuple as a key in the dictionary. Keep a count of how many times each tuple has occurred.
def tuple_from_digits(num):
# Convert the number to a tuple of its digit frequencies
digit_freq = [0] * 10 # 10 digits (0-9)
for digit in str(num):
digit_freq[int(digit)] += 1
return tuple(digit_freq)
def solution(a):
digit_anagrams_count = 0
tuple_count = defaultdict(int)
for num in a:
# Get the tuple representing digit frequencies
digit_tuple = tuple_from_digits(num)
# Update the count of digit anagrams
digit_anagrams_count += tuple_count[digit_tuple]
# Increment the count of this tuple for future occurrences
tuple_count[digit_tuple] += 1
return digit_anagrams_count
# Example usage:
a = [25, 35, 872, 228, 53, 278, 872]
result = solution(a)
print(result) # Output should be 4