Came across a question awhile ago, and it got me wondering what the best way to go about this would be.
Would like to have an method which takes an input string and returns a boolean whether or not the given string has only 1 character duplicated in it (can be duplicated multiple times)
ie: 'abca' -> True , 'abab' -> False, 'aaaa' -> True
My solution seemed a bit convoluted and I wanted to know a better way
#!/usr/bin/env python
import collections
def hasOnlyOneDuplicate(string):
# turn string into a dictionary with counter and obtain a list of all the values/occurences of each letter
values = list(collections.Counter(string).values())
# then we remove all the numbers that are a 1
result = filter(lambda a: a!=1, values)
return len(result) == 1
If the given string only had 1 duplicated character in there, the length of the remaining list should be 1, right? Otherwise there were multiple characters duplicated
Thanks for the help