Hackerrank Solution: Regex Substitution in Python

Question: Regex Substitution - Hacker Rank (Python Regex and Parsing)

The re.sub() tool (sub stands for substitution) evaluates a pattern and, for each valid match, it calls a method (or lambda).
The method is called for all matches and can be used to modify strings in different ways.
The re.sub() method returns the modified string as an output.

Transformation of Strings

Advertisement

Code:

import re

#Squaring numbers
def square(match):
number = int(match.group(0))
return str(number**2)

print re.sub(r"\d+", square, "1 2 3 4 5 6 7 8 9")

Output

1 4 9 16 25 36 49 64 81

Replacements in Strings

Code:

import re

html = """
<head>
<title>HTML</title>
</head>
<object type="application/x-flash" 
  data="your-file.swf" 
  width="0" height="0">
  <!-- <param name="movie"  value="your-file.swf" /> -->
  <param name="quality" value="high"/>
</object>
"""

print re.sub("(<!--.*?-->)", "", html) #remove comment

Output:

<head>
<title>HTML</title>
</head>
<object type="application/x-flash" 
  data="your-file.swf" 
  width="0" height="0">

  <param name="quality" value="high"/>
</object>

Task:

Advertisement

You are given a text of N lines. The text contains && and || symbols.
Your task is to modify those symbols to the following:

&& → and
|| → or

Both && and || should have a space ” ” on both sides.

Input format:

The first line contains the integer, N.
The next N lines each contain a line of the text.

Constraints:

  • 0 < N < 100
  • Neither && nor || occur in the start or end of each line.

Sample input:

11
a = 1;
b = input();

if a + b > 0 && a - b < 0:
    start()
elif a*b > 10 || a/b < 1:
    stop()
print set(list(a)) | set(list(b)) 
#Note do not change &&& or ||| or & or |
#Only change those '&&' which have space on both sides.
#Only change those '|| which have space on both sides.

Sample Output:

a = 1;
b = input();

if a + b > 0 and a - b < 0:
    start()
elif a*b > 10 or a/b < 1:
    stop()
print set(list(a)) | set(list(b)) 
#Note do not change &&& or ||| or & or |
#Only change those '&&' which have space on both sides.
#Only change those '|| which have space on both sides. 

 

Possible Solutions:

Let us now explore some possible solutions that we can use in order to pass the test on Hacker Rank. There can be many approaches to finding the solution using Python language. We will use the following three ways.

 

Solution-1: Using for loop

We will first import the regular expression module and then will use the for loop to iterate in a range provided by the user. Then we will use the regular expressions to get the required output. Let's start the coding part.

# importing the module
import re

# using for loop
for i in range(int(input())):
    
    # using re.sub method and taking input
    s = re.sub("(?<=\s)&&(?=\s)", "and", input())
    
    #printing the required output
    print(re.sub("(?<=\s)\|\|(?=\s)", "or", s))

Input:

We will take randomly any string as input that contains && and || symbols and the above Python code will change them to the required output:

1
Do you like apples || orange && banana?

Output:

Advertisement
Do you like apples or orange and banana?

As you can see, the symbols have been changed to the required values.

 

Solution-2: Lambda function

A Lambda Function in Python programming is an anonymous function or a function having no name. It is a small and restricted function having no more than one line. Just like a normal function, a Lambda function can have multiple arguments with one expression. We will now use lambda in our Python program to solve the question.

# importing the re module
import re

# using for loop
for i in range(int(input())):
    
    # using re.sub method and lambda function
    print(re.sub(r'(?<= )(&&|\|\|)(?= )', lambda x: 'and' if x.group() == '&&' else 'or', input()))

Input:

1
Do you like apples || orange && banana?

Output:

Do you like apples or orange and banana?

As you can see, we get the required output as was mentioned in the description of the question.

 

Solution-3: Using if-else statements

Now, we will create a function that will check for the && and || symbols using if-else statements. Let's start the coding part.

Advertisement
# importing the re module
import re

# taking input from user
n = int(input())

# using user defined function
def check_replacement_required(match):
    
    # using if else statements to check
    st = str(match.group(0))
    if st == "||":
        return "or"
    elif st == "&&":
        return "and"

# using for loop to 
for i in range(n):
    
    # taking input from user and calling the function
    s = input()
    p = "(?<=[ ])[|]{2}(?=[ ])|(?<=[ ])[&]{2}(?=[ ])"
    print(re.sub(p, check_replacement_required, s))

Input:

1 
Do you like apples || orange && banana?

Output:

Do you like apples or orange and banana?

As you can see, we get the required output.

 

Summary

In this short article, we come up with multiple solutions for the Regex Substitution question on Hacker rank. We used the for loop, lambda function, and if-else statements to find the desired solution in various ways. You can choose any of them.

 

Further Reading

Question on Hacker Rank: Regex Substitution

 

Related Keywords: regex substitution hackerrank solution python, hackerrank regex solution, hackerrank regex solution python, hackerrank regex solution python3, hackerrank regex substituion solution

Advertisement

 

Didn't find what you were looking for? Perform a quick search across GoLinuxCloud

If my articles on GoLinuxCloud has helped you, kindly consider buying me a coffee as a token of appreciation.

Buy GoLinuxCloud a Coffee

For any other feedbacks or questions you can either use the comments section or contact me form.

Thank You for your support!!

Leave a Comment

X