Sunday, November 17, 2024
Google search engine
HomeLanguagesPython – Distance between occurrences

Python – Distance between occurrences

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 = 'neveropen'
 
# 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 : neveropen
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 = 'neveropen'
 
# 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 : neveropen
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 = 'neveropen'
 
# 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))


Output

The original string is : neveropen
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 = 'neveropen'
 
#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))


Output

The original string is : neveropen
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 :

  1. Initialize the input string test_str and the character K to search for.
  2. 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.
  3. 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.
  4. If the character is equal to K and this is the first occurrence, update the first variable to the current index i.
  5. 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.
  6. 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.
  7. 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 = 'neveropen'
 
#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))


Output

The original string is : neveropen
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.

Dominic Rubhabha-Wardslaus
Dominic Rubhabha-Wardslaushttp://wardslaus.com
infosec,malicious & dos attacks generator, boot rom exploit philanthropist , wild hacker , game developer,
RELATED ARTICLES

Most Popular

Recent Comments