Search This Blog

HackerRank Handson - Python - Match Pattern and Replace - Course Id 55195 - Hackerearth Python

 Match Pattern and Replace

Write a function subst which replaces a pattern matching portion with another value. Using subst, replace all the words ROAD with RD in the following 

addr = ['100 NORTH MAIN ROAD', '100 BROAD ROAD APT.', 'SAROJINI DEVI ROAD', 'BROAD AVENUE ROAD']. Use the Test against custom input box to output the result for debugging. Use print(res) to display the output


1. Write a function subst which replaces a pattern matching portion with another value.

2. Using subst, replace all the words ROAD with RD in the following:

addr = ['100 NORTH MAIN ROAD',
  '100 BROAD ROAD APT.',
  'SAROJINI DEVI ROAD',
  'BROAD AVENUE ROAD']

3. Use the Test against custom input box to output the result for debugging

4. Use print(res) to display the output

Expected Output:

['100 NORTH MAIN RD.','100 BROAD RD.APT.','SAROJINI DEVI RD.','BROAD           AVENUE RD.']

Answer:

#!/bin/python3

import sys
import os
import io
import re


# Complete the function below.
def subst(pattern, replace_str, string):
    #susbstitute pattern and return it
    ki=""
    match= pattern.finditer(string)
    for j in match: ki=re.sub('[^A-Z]ROAD',' RD.',j.group(0))
    if ki[-1]!='.':
        ki+='.'
    return ki
def main():
    addr = ['100 NORTH MAIN ROAD',
            '100 BROAD ROAD APT.',
            'SAROJINI DEVI ROAD',
            'BROAD AVENUE ROAD']
            
    #Create pattern Implementation here 
    new_address=[]
    k='RD'
    pattern=re.compile(r'[A-Z0-9 ]+ROAD\s*[A-Z]*.*')
    for i in addr:
        r = subst(pattern, k, i)
        new_address.append(r)
    #Use subst function to replace 'ROAD' to 'RD.',Store as new_address
    return new_address

'''For testing the code, no input is required'''

if __name__ == "__main__":
    f = open(os.environ['OUTPUT_PATH'], 'w')

    res = main();
    f.write(str(res) + "\n")


    f.close()

*Click on image to open:






No comments:

Post a Comment

If you have any doubts, Please let us know.