Python - Mid occurrence of K in string
Last Updated :
07 Apr, 2023
Given a String, the task is to write a Python program to extract the mid occurrence of a character.
Input : test_str = "geeksforgeeks is best for all geeks", K = 'e'
Output : 10
Explanation : 7 occurrences of e. The 4th occurrence [mid] is at 10th index.
Input : test_str = "geeksforgeeks is best for all geeks", K = 'g'
Output : 8
Explanation : 3 occurrences of g. The 2nd occurrence [mid] is at 8th index.
Method #1 : Using enumerate() + list comprehension
In this, we perform the task of getting all occurrences using list comprehension and enumerate gets all indices. Post that the middle element of the list is printed to get mid occurrence of a character.
Python3
# Python3 code to demonstrate working of
# Mid occurrence of K in string
# Using find() + max() + slice
# initializing string
test_str = "geeksforgeeks is best for all geeks"
# printing original string
print("The original string is : " + str(test_str))
# initializing K
K = 'e'
# getting all the indices of K
indices = [idx for idx, ele in enumerate(test_str) if ele == K]
# getting mid index
res = indices[len(indices) // 2]
# printing result
print("Mid occurrence of K : " + str(res))
Output:
The original string is : geeksforgeeks is best for all geeks
Mid occurrence of K : 10
Time Complexity: O(n)
Space Complexity: O(n)
Method #2 : Using finditer() + list comprehension + regex
In this, the character is found using regex and finditer(). The mid occurrence is the mid element of the indices list.
Python3
# Python3 code to demonstrate working of
# Mid occurrence of K in string
# Using finditer() + list comprehension + regex
import re
# initializing string
test_str = "geeksforgeeks is best for all geeks"
# printing original string
print("The original string is : " + str(test_str))
# initializing K
K = 'e'
# getting all the indices of K
# using regex
indices = [ele.start() for ele in re.finditer(K, test_str)]
# getting mid index
res = indices[len(indices) // 2]
# printing result
print("Mid occurrence of K : " + str(res))
Output:
The original string is : geeksforgeeks is best for all geeks
Mid occurrence of K : 10
Time Complexity: O(n)
Auxiliary Space: O(n)
Approach#3: Using a loop to count the occurrences of K
This approach first counts the total number of occurrences of the character K in the given string. Then, it calculates the mid index by dividing the count by 2 and taking the ceiling value. Finally, it iterates over the string again and counts the occurrences of K until it reaches the mid index, and returns the index of that mid occurrence. If there is no mid occurrence, it returns -1.
Algorithm
1. Initialize a count variable to 0.
2. Traverse the string character by character and increment the count variable by 1 if the character is equal to K.
3. Compute the mid occurrence of K by dividing the count variable by 2 and rounding up.
4. Traverse the string again and keep track of the number of occurrences of K seen so far.
5. If the number of occurrences seen so far is equal to the mid occurrence, return the current index.
6. Return -1 if the mid occurrence is not found.
Python3
import math
def mid_occurrence(str_, K):
count = 0
for i in range(len(str_)):
if str_[i] == K:
count += 1
mid = math.ceil(count / 2)
count = 0
for i in range(len(str_)):
if str_[i] == K:
count += 1
if count == mid:
return i
return -1
str_ = "geeksforgeeks is best for all geeks"
K='e'
print(mid_occurrence(str_, K))
Time complexity: O(n), where n is the length of the string.
Auxiliary Space: O(1).
Approach#4: Using the lambda function
In this approach, the lambda function takes two arguments test_str and K, which are the string and the character to be searched for, respectively.
The lambda function uses a generator expression [ele.start() for ele in re.finditer(K, test_str)] to find all the indices of the character K in the string test_str using regex.
The lambda function then calculates the middle index of the indices list indices using (lambda indices: indices[len(indices) // 2] if indices else -1)(...). If the indices list is not empty, it returns the middle index, otherwise, it returns -1.
Below is the code for the above approach:
Python3
import re
mid_occurrence = lambda test_str, K: (lambda indices:
indices[len(indices) // 2] if indices else -1
)([ele.start() for ele in re.finditer(K, test_str)])
# initializing string
test_str = "geeksforgeeks is best for all geeks"
# printing original string
print("The original string is : " + str(test_str))
# initializing K
K = 'e'
# getting mid index
res = mid_occurrence(test_str, K)
# printing result
print("Mid occurrence of K : " + str(res))
OutputThe original string is : geeksforgeeks is best for all geeks
Mid occurrence of K : 10
Time complexity: O(n)
Auxiliary Space: O(m), where m is the number of occurrences of the character K in the string test_str.
METHOD 5:
APPROACH: Using for loop and counter variable.
The given problem can be solved using a simple iteration over the string while keeping track of the count of the character K. Once the count reaches the mid occurrence of K in the string, the index of that occurrence can be returned.
ALGORITHM:
1.Initialize a counter variable to 0.
2.Iterate over the string using a for loop and an index variable.
3.If the character at the current index is equal to the given character K, increment the counter variable.
4.Check if the counter is equal to the mid occurrence of K in the string, which can be calculated by dividing the total count of K by 2 and adding 1. 5.If the condition is true, return the current index.
6.If the loop completes without finding the mid occurrence of K, return -1.
Python3
test_str = "geeksforgeeks is best for all geeks"
K = 'e'
count = 0
for i in range(len(test_str)):
if test_str[i] == K:
count += 1
if count == (test_str.count(K) // 2 + 1):
print(i)
break
Time Complexity:
The time complexity of this approach is O(n), where n is the length of the input string. This is because we are iterating over the string once.
Auxiliary Space:
The space complexity of this approach is O(1), because we are only using a constant amount of extra space for the counter variable and the loop variable.
Similar Reads
Python | Find last occurrence of substring
Sometimes, while working with strings, we need to find if a substring exists in the string. This problem is quite common and its solution has been discussed many times before. The variation of getting the last occurrence of the string is discussed here. Let's discuss certain ways in which we can fin
8 min read
Python - All occurrences of substring in string
A substring is a contiguous occurrence of characters within a string. Identifying all instances of a substring is important for verifying various tasks. In this article, we will check all occurrences of a substring in String.Using re.finditer()re.finditer() returns an iterator yielding match objects
3 min read
Python - Characters Index occurrences in String
Sometimes, while working with Python Strings, we can have a problem in which we need to check for all the characters indices. The position where they occur. This kind of application can come in many domains. Lets discuss certain ways in which this task can be performed. Method #1 : Using set() + reg
6 min read
Python - Slice from Last Occurrence of K
Sometimes, while working with Python Strings, we can have a problem in which we need to perform the task of performing characters stripping on the last occurrence of element. This can have applications in which data is involved. Lets discuss certain ways in which this task can be performed. Method #
3 min read
Find Length of String in Python
In this article, we will learn how to find length of a string. Using the built-in function len() is the most efficient method. It returns the number of items in a container. Pythona = "geeks" print(len(a)) Output5 Using for loop and 'in' operatorA string can be iterated over, directly in a for loop.
2 min read
Split string on Kth Occurrence of Character - Python
The task is to write Python program to split a given string into two parts at the KáµÊ° occurrence of a specified character. If the character occurs fewer than K times return the entire string as the first part and an empty string as the second part. For example, in the string "a,b,c,d,e,f", splitting
3 min read
Python - Maximum Consecutive Substring Occurrence
Sometimes, while working with Python, we can have a problem in which we must check for substrings occurring in consecutive repetition. This can have applications in data domains. Let us discuss a way in which this task can be performed. Method #1: Using max() + re.findall() A combination of the abov
5 min read
Get Second Occurrence of Substring in Python String
We are given a string and a substring, and our task is to find the index of the second occurrence of that substring within the string. This means we need to identify not just if the substring exists, but where it appears for the second time. For example, if we have a string like "hello world, hello
2 min read
Split on last occurrence of delimiter-Python
The goal here is to split a string into two parts based on the last occurrence of a specific delimiter, such as a comma or space. For example, given the string "gfg, is, good, better, and best", we want to split it into two parts, everything before the last comma-space and everything after it. The r
3 min read
Python - Extract String after Nth occurrence of K character
Given a String, extract the string after Nth occurrence of a character. Input : test_str = 'geekforgeeks', K = "e", N = 2 Output : kforgeeks Explanation : After 2nd occur. of "e" string is extracted. Input : test_str = 'geekforgeeks', K = "e", N = 4 Output : ks Explanation : After 4th occur. of "e"
7 min read