+

Find all duplicate characters from a string in Python

One line is given. Our task &find those characters, the frequency of which in the given string is more than one. 

As an example, we see that the string “Hello World. Let`s learn Python ”, so the algorithm will find letters that occur multiple times. In this case, the output will look like this:


 e: 3 l: 4 o, 3) & lt; space & gt; : 4 r: 2 t: 2 n: 2 

We use Python Collections to implement this problem. From the collection, we can get the Counter () method. The Counter () method is used to count the objects in the hash table. In this case, it separates characters from text and makes each character a dictionary key, and the number of characters &this is the value of these 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 

Sample Code

 from collections import Counter defcalc_char_freq (str ing): 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) & gt; 1: # for all different keys, list the letters and frequencies print ("(" + key + "," + str (freq_count.g et (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) 



Get Solution for free from DataCamp guru