Skip to content

Instantly share code, notes, and snippets.

@dedeco
Created August 19, 2020 00:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dedeco/699cba0095cc43fa09c2fe641186a926 to your computer and use it in GitHub Desktop.
Save dedeco/699cba0095cc43fa09c2fe641186a926 to your computer and use it in GitHub Desktop.
Anagram substring quantity
from collections import defaultdict
def count_anagram(str):
subs = defaultdict(int)
for i in range(len(str)):
for j in range(1, len(str) + 1):
if j > i:
subs[''.join(sorted(str[i:j]))] += 1
print(subs)
count = 0
for k, qty in subs.items():
if qty > 1:
count += int(qty * (qty - 1) / 2)
return count
if __name__ == "__main__":
print([count_anagram(x) for x in ['abba', 'banana']])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment