Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python - Find the number of duplicates in a string text

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
like image 315
M. Abra Avatar asked Jun 10 '17 23:06

M. Abra


People also ask

How do you find duplicates in a string?

The duplicate characters are found in the string using a nested for loop. Then these characters are displayed.


2 Answers

One simple way of doing it is :

def duplicate_count(s):
    return len([x for x in set(s) if s.count(x) > 1])
like image 144
Antoine Boisier-Michaud Avatar answered Nov 14 '22 22:11

Antoine Boisier-Michaud


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)
like image 37
Bubble Bubble Bubble Gut Avatar answered Nov 14 '22 22:11

Bubble Bubble Bubble Gut