+

TCS National Qualifier 2 Coding Question.

You are given a string, and your task is — print the frequency of each character.

Direction for solving the problem

1. Take a line from STDIN.

 aaaabbBcddee 

2 . Get all the different characters in a given string using set ().

 set = {a, b, B, c, d, e} # unordered set 

3. Iterate for different characters (len (set)), because we only need to print a character once and it counts in the input line

 range 0 to 5 ie total 6 element 

4. In each iteration, take the first character and output it and its count.

 now for 0 input_string [0] is `a` and its count is 4 

5 Remove all occurrences of the first character, this is will make the next character first.

 remove `a` by replacing all` a` in string by "" new input string will be bbBcddee 

6. Repeat the same process, go to step 4.
7. Either print the value to STDOUT on each iteration (python3) or print in one go (python2), your output will be the same as

 a4b2B1c1d2e2 
< p> Examples:

 Input: aaaabbBcddee Output: a4b2B1c1d2e2 Input: aazzZ Output: a2z2Z1 

# Python2 code here

input_string = raw_input ()

temp_string = ""

for _ in range ( len ( set (input_string))):

  temp_string + = input_string [ 0 ] + str (input_string.count (input_string [ 0 ])) 

input_string = input_string.replace (input_string [ 0 ]," ")

print temp_string

# Python3 code here

input_string = input ()

for _ in range ( len ( set (input_string))):

  print (input_string [ 0 ] + str (input_string.count (input_string [ 0 ])), end = "")

input_string = input_string.replace (input_string [ 0 ]," ")

Write your interview experience or email it to [email protected]

Get Solution for free from DataCamp guru