Find All Duplicate Characters from a String using Python

PythonProgrammingServer Side Programming

One String is given. Our task is to find those characters whose frequency is more than one in the given string.

As an example, we can see that the string “Hello World. Let’s learn Python” so the algorithm will find those letters which are occurring multiple times. In this case, the output will look like this -

e : 3
l : 4
o , 3)
<space> : 4 
r : 2
t : 2
n : 2

To implement this problem we are using Python Collections. From the collection, we can get the Counter() method. The Counter() method is used to count the hashtable objects. In this case, it separates the characters from the text and makes each character as a key of the dictionary, and the character count is the value of those keys.

Algorithm

Step 1: Find the key-value pair from the string, where each character is key and character counts are the values.
Step 2: For each key, check whether the value is greater than one or not. 
Step 3: If it is greater than one then, it is duplicate, so mark it. Otherwise, ignore the character 

Example Code

from collections import Counter
defcalc_char_freq(string):
   freq_count = Counter(string) # get dictionary with letters as key and frequency as value
   for key in freq_count.keys():
      if freq_count.get(key) > 1: # for all different keys, list the letters and frequencies
         print("(" + key + ", " + str(freq_count.get(key)) + ")")
      myStr = 'Hello World. Let’s learn Python'    
      calc_char_freq(myStr)

Output

(e, 3)
(l, 4)
(o, 3)
( , 4)
(r, 2)
(t, 2)
(n, 2)
raja
Published on 26-Sep-2018 08:20:40
Advertisements