I want to write a function that returns the number of alphabetic characters and numeric digits that occur more than once in an input string.
Sample example: "aabbccd" should return 3 since "a","b" and "c" all have duplicates. Same for "aaabbccd", that would return 3 as well.
Here is what I did, but it seems that there's something wrong with my code. It worked on some cases but apparently it does not on others.
def duplicate_count(text):
count=0
for i in range(len(text)-1):
for j in range(i+1,len(text)):
if text[i]==text[j]:
count+=1
break
break
return count
The duplicate characters are found in the string using a nested for loop. Then these characters are displayed.
One simple way of doing it is :
def duplicate_count(s):
return len([x for x in set(s) if s.count(x) > 1])
This one would be more concise:
import numpy as np
def duplicate_count(text):
#elem is an array of the unique elements in a string
#and count is its corresponding frequency
elem, count = np.unique(tuple(text), return_counts=True)
return np.sum(count>1)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With