Last active
February 27, 2024 22:09
-
-
Save ricardo1512/da7a5bf3ae3d1a99f480a15336e3c361 to your computer and use it in GitHub Desktop.
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
# https://www.hackerrank.com/challenges/sherlock-and-anagrams/problem | |
def sherlockAndAnagrams(s): | |
from collections import defaultdict | |
from math import factorial | |
# Creating a dictionary of anagrams: | |
dictionary = defaultdict(lambda: 0) | |
for i in range(len(s)): | |
for j in range(i + 1, len(s) + 1): | |
sorted_sequence = sorted(list(s[i:j])) | |
dictionary["".join(sorted_sequence)] += 1 | |
# Calculating and adding the number of combinations per anagram-item: | |
combinations = 0 | |
for item, value in dictionary.items(): | |
if value >= 2: | |
combinations += factorial(value) // (2 * factorial(value - 2)) | |
return combinations |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment