Monday, December 2, 2019

Re.start() & Re.end() - Hacker Rank Solution

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 .
Your task is to find the indices of the start and end of string  in .
Input Format
The first line contains the string .
The second line contains the string .
Constraints

Output Format
Print the tuple in this format: (start _indexend _index).
If no match is found, print (-1, -1).
Sample Input
aaadaa
aa
Sample Output
(0, 1)  
(1, 2)
(4, 5)

Re.start() & Re.end() - Hacker Rank Solution

We can solve this by using forward lookahead, together with start() and end().

import re
S = raw_input()
k = raw_input()
anymatch = 'No'
for m in re.finditer(r'(?=('+k+'))',S):
    anymatch = 'Yes'
    print (m.start(1),m.end(1)-1)
if anymatch == 'No':
    print (-1, -1)
import re
S = input()
k = input()
anymatch = 'No'
for m in re.finditer(r'(?=('+k+'))',S):
    anymatch = 'Yes'
    print((m.start(1),m.end(1)-1))
if anymatch == 'No':
    print((-1, -1))

No comments:

Post a Comment

Powered by Blogger.