Re.start() & Re.end() in Python - HackerRank Solution
Problem :
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 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | # Re.start() & Re.end() in Python - Hacker Rank Solution # Python 3 # Enter your code here. Read input from STDIN. Print output to STDOUT # Re.start() & Re.end() in Python - Hacker Rank Solution START import re S, k = input(), input() matches = re.finditer(r'(?=(' + k + '))', S) anymatch = False for match in matches: anymatch = True print((match.start(1), match.end(1) - 1)) if anymatch == False: print((-1, -1)) # Re.start() & Re.end() in Python - Hacker Rank Solution END |
Solution 2 :
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | # Re.start() & Re.end() in Python - Hacker Rank Solution # Python 3 # Enter your code here. Read input from STDIN. Print output to STDOUT # Re.start() & Re.end() in Python - Hacker Rank Solution START import re string = input() substring = input() pattern = re.compile(substring) match = pattern.search(string) if not match: print('(-1, -1)') while match: print('({0}, {1})'.format(match.start(), match.end() - 1)) match = pattern.search(string, match.start() + 1) # Re.start() & Re.end() in Python - Hacker Rank Solution END |
Disclaimer :-
the above hole problem statement is given by hackerrank.com but the solution is generated by the codeworld19 authority if any of the query regarding this post or website fill the following contact form thank you.