import math
import os
import random
import re
import sys
# Complete the sherlockAndAnagrams function below.
from collections import defaultdict
def get_all_substrings(s):#先提出所有的子集
n=len(s)
sublist=[]
for i in range(n):
for j in range(i+1,n+1):
sublist.append(s[i:j])
return sublist
def sherlockAndAnagrams(s):
sublist=get_all_substrings(s)
zd=defaultdict(int)
count=0
for sub in sublist: #子集中元素相同,且每个元素的个数相同的子集,出现的次数用字典储存
zd[str(sorted(sub))] +=1 #注意用sorted而不是set!!!
for ele in zd.items(): #字典中,value>1的元素中每两个算一对
if ele[1]!=1:
count += ele[1]*(ele[1]-1)/2
return int(count)