Python - Distance between occurrences
Last Updated :
22 Apr, 2023
Sometimes, while working with Python Strings, we can have a task in which we need to find the indices difference between occurrences of a particular character. This can have applications in domains such as day-day programming. Let us discuss certain ways in which this task can be done.
Method #1: Using index():
This is one of the ways in which we can solve this problem. In this, we use the power of index() to get the Nth index of occurrence and subtract it from initial occurrence.
Python3
# Python3 code to demonstrate working of
# Distance between occurrences
# Using index()
# initializing string
test_str = 'geeksforgeeks'
# printing original string
print("The original string is : " + str(test_str))
# initializing K
K = 'k'
# Distance between occurrences
# Using index()
res = test_str.index(K, test_str.index(K) + 1) - test_str.index(K)
# printing result
print("The character occurrence difference is : " + str(res))
Output : The original string is : geeksforgeeks
The character occurrence difference is : 8
Method #2: Using find() + rfind():
The combination of above functions can be used to solve this problem. In this, we find the first occurrence using find() and next(last) using rfind().
Python3
# Python3 code to demonstrate working of
# Distance between occurrences
# Using find() + rfind()
# initializing string
test_str = 'geeksforgeeks'
# printing original string
print("The original string is : " + str(test_str))
# initializing K
K = 'k'
# Distance between occurrences
# Using find() + rfind()
res = test_str.rfind(K) - test_str.find(K)
# printing result
print("The character occurrence difference is : " + str(res))
Output : The original string is : geeksforgeeks
The character occurrence difference is : 8
Method #3: Without any built-in methods
Python3
# Python3 code to demonstrate working of
# Distance between occurrences
# initializing string
test_str = 'geeksforgeeks'
# printing original string
print("The original string is : " + test_str)
# initializing K
K = 'k'
# Distance between occurrences
x = []
for i in range(0, len(test_str)):
if(test_str[i] == K):
x.append(i)
res = x[1]-x[0]
# printing result
print("The character occurrence difference is : " + str(res))
OutputThe original string is : geeksforgeeks
The character occurrence difference is : 8
The Time and Space Complexity for all the methods are the same:
Time Complexity: O(n)
Space Complexity: O(n)
Approach 4: Using re module
Python3
import re
#initializing string
test_str = 'geeksforgeeks'
#printing original string
print("The original string is : " + test_str)
#initializing K
K = 'k'
#Distance between occurrences
#Using re module
matches = re.finditer(K, test_str)
indices = [match.start() for match in matches]
res = indices[1] - indices[0]
#printing result
print("The character occurrence difference is : " + str(res))
OutputThe original string is : geeksforgeeks
The character occurrence difference is : 8
Time complexity: O(n)
Auxiliary Space: O(n)
Explanation:
The re module is used to search for all the occurrences of a character in the given string.
The re.finditer method returns an iterator yielding match objects for all non-overlapping matches.
The start method of the match object returns the starting index of the match.
We store the starting indices of all the matches in a list indices and calculate the difference between the first and second occurrence.
Method 4 : use a loop and keep track of the indices of the character.
step-by-step approach :
- Initialize the input string test_str and the character K to search for.
- Initialize two variables first and second to keep track of the indices of the first and second occurrence of the character. Set them to -1 initially to indicate that the character has not been found yet.
- Loop through the indices of the string using the range function and the len function. For each index i, check if the character at that index is equal to the search character K.
- If the character is equal to K and this is the first occurrence, update the first variable to the current index i.
- If the character is equal to K and this is the second occurrence, update the second variable to the current index i and break out of the loop, since we only need to find the first two occurrences.
- If the loop completes without finding two occurrences of the character, both first and second will still be equal to -1. In that case, print an error message indicating that the character was not found twice in the string.
- Otherwise, calculate the distance between the indices of the two occurrences by subtracting first from second and print the result.
Python3
import re
#initializing string
test_str = 'geeksforgeeks'
#printing original string
print("The original string is : " + test_str)
#initializing K
K = 'k'
#Distance between occurrences
#Using re module
matches = re.finditer(K, test_str)
indices = [match.start() for match in matches]
res = indices[1] - indices[0]
#printing result
print("The character occurrence difference is : " + str(res))
OutputThe original string is : geeksforgeeks
The character occurrence difference is : 8
Time complexity of this approach is O(n) since we are looping through the entire string.
Auxiliary space is O(1) since we are only using a few variables to store the indices.
Similar Reads
Python | Maximum distance between elements Sometimes, while working with lists, we can have a problem in which we need to find maximum distance between reoccurring elements. This kind of problem can have application in competitive programming and web development domain. Let's discuss certain way in which this task can be performed. Method 1:
6 min read
Python - Nearest occurrence between two elements in a List Given a list and two elements, x and y find the nearest occurrence index of element x from element y. Input : test_list = [2, 4, 5, 7, 8, 6, 3, 8, 7, 2, 0, 9, 4, 9, 4], x = 4, y = 6 Output : 1 Explanation : 4 is found at 1, 12 and 14th index, 6 is at 5th index, nearest is 1st index.Input : test_list
5 min read
Difference between two Lists in Python The difference between two lists in Python refers to the elements that are present in one list but not in the other. For example, finding the difference between lists a = [1, 2, 3, 4] and b = [3, 4, 5, 6] can result in [1, 2] by removing the common elements (3 and 4).Using setSet operations are most
3 min read
Python - First Occurrence of One List in Another We are given two lists, and our task is to find the first occurrence of the second list as a contiguous subsequence in the first list. If the second list appears as a subsequence inside the first list, we return the starting index of its first occurrence; otherwise, we return -1. For example, if a =
3 min read
Python - Actual order index distance Sometimes we have an unsorted list and we wish to find the actual position the elements could be when they would be sorted, i.e we wish to construct the list which could give the position distance to each element destined if the list was sorted. This has a good application in web development and com
3 min read
Python | Equidistant element list Sometimes, while working with Python list we can have a problem in which we need to construct the list in which the range is auto computed using the start, end and length parameters. The solution of this problem can have many applications. Let's discuss a way in which this task can be performed. Met
2 min read