find the second occurrence in string Python

This Python tutorial is about how to find the second-most frequent character or the second occurrence in a string. We will discuss various methods here to identify the Characters and Symbols which are used second-most frequently in a string. Let’s look at some problems and then learn them with examples.

second occurrence in string:

Given a character string, find the second occurrence in it.

  • If the input string is “aaabbc”, then the Second most frequent character is ‘b’.
  • Similarly, If the input string is “oooibbeeeee”, then the Second most frequent character is ‘o’.
  • If the input string is “iiiuue”, then the Second most frequent character is ‘a.
  • An interesting situation arises when the input string is “aabbcc”. Then there will be no second occurrence.

second occurrence for char stirng

Let’s look at the solution. A simple logical solution is to start from the first character, count its occurrences, then the second character, and so on. While counting these occurrences keep track of the most occurred and the second most occurred number or alphabet.

Step 1:

First of all, we will have to create a string. Let’s say string str = “aaabbc”. Secondly, we will have to initialize the count list with a size equal to 256 and a value of 0.

str = aaabbc
NO_OF_CHARS = 256
count = [0] * NO_OF_CHARS
 

step 2:

Now we will have to count the number of occurrences of every character. We will use len(str) function to find the length of the string/

for i in range(len(str)) :
  count[ord(str[i])] += 1

step 3:

Now we will have to traverse through the count list and find the second most occurring character.



first, second = 0, 0

for i in range(NO_OF_CHARS) :
  if count[i] > count[first] :
     second = first
     first = i
  elif (count[i] > count[second] and 
      count[i] != count[first]):
      second = i

Step 4:

Now we will store the result and display the output.

res = chr(second)
if res != '\0' :
        print("Second most frequent char is", res)
else :
        print("No second most frequent character")

source code:

str = "aaaabbbc"

NO_OF_CHARS = 256
count = [0] * NO_OF_CHARS

for i in range(len(str)) :
  count[ord(str[i])] += 1

first, second = 0, 0

for i in range(NO_OF_CHARS) :
  if count[i] > count[first] :
     second = first
     first = i
  elif (count[i] > count[second] and 
      count[i] != count[first]):
      second = i

 
res = chr(second)
if res != '\0' :
        print("Second most frequent char is", res)
else :
        print("No second most frequent character")
Second Occurrence In String

Second Occurrence for symbols string

This code works well for symbols too. Let’s see the output.

symbols second occurrence in python

If you have any questions related to Python or Matlab Contact Us. Don’t forget to leave feedback in the comment box.

Leave a Comment

Your email address will not be published. Required fields are marked *