Re.start() & Re.end()

You can find this problem on hakerrank


Problem Statement:

start() & end() These expressions return the indices of the start and end of the substring matched by the group.

Code

>>> import re 
>>> m = re.search(r'\d+','1234')
>>> m.end() 
4 
>>> m.start() 
0 

Task You are given a string S. Your task is to find the indices of the start and end of string K in S.


Input Format The first line contains the string S. The second line contains the string K.

Constraints 0 < len(S) < 100

0 < len(K) < len(S)

Output Format Print the tuple in this format: (start _index, end _index). If no match is found, print (-1, -1).


Sample Input

aaadaa 
aa 

Sample Output

(0, 1) 
(1, 2) 
(4, 5)

Solution 1

Using re:

import re
s = input()
k = input()

substring = re.compile(k)
r = substring.search(s)

if not r: 
    print("(-1, -1)")
else:
    while r:
        print("({}, {})".format(r.start(), r.end() - 1))
        r = substring.search(s,r.start() + 1)

Solution 2

Without using any library:

S = input()
k = input()
check = False
for i in range(len(S)-len(k)+1):
    if S[i:i+len(k)]==k:
        check = True
        print("({}, {})".format(i,i+len(k)-1))
if check==False:
    print("(-1, -1)")

Happy Coding!

Follow us on Instagram @programmersdoor

Join us on Telegram @programmersdoor


Please write comments if you find any bug in above code/algorithm, or find other ways to solve the same problem.

Follow Programmers Door for more.

#blog #interview #placement #learn #ComputerScience #Engineering

        Contact Us

programmersdoor@gmail.com

  • LinkedIn
  • Facebook
  • Instagram

©2023 by Programmers Door