Created
August 19, 2020 00:46
-
-
Save dedeco/699cba0095cc43fa09c2fe641186a926 to your computer and use it in GitHub Desktop.
Anagram substring quantity
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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