

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Program to enclose pattern into bold tag in Python?
Suppose we have a text and a list of strings called patterns, we have to define an embolden function where all substrings in text that match any string in the given patterns are wrapped in and tags. If any two patterns are adjacent or overlap, they should be merged into one tag.
So, if the input is like text = "thisissampleline" patterns = ["this", "issam", "sample"], then the output will be "a<b>bc</b>d<b>ef</b>g", as bc and ef match the text and are wrapped in <b> and </b> tags.
To solve this, we will follow these steps
n := size of text
bold := a list of size n, and fill with False values
for i in range 0 to n, do
for each p in patterns, do
if substring of text[from index i to end] is starts with p, then
for j in range 0 to size of p, do
bold[i + j] := True
ans := blank string
for i in range 0 to n, do
if bold[i] and (i is same as 0 or bold[i - 1] is false) , then
ans := ans concatente "<b>"
ans := ans + text[i]
if bold[i] and (i is same as n - 1 or bold[i + 1] is false) , then
ans := ans concatenate "</b>"
return ans
Let us see the following implementation to get better understanding
Example
class Solution: def solve(self, text, patterns): n = len(text) bold = [False] * n for i in range(n): for p in patterns: if text[i:].startswith(p): for j in range(len(p)): bold[i + j] = True ans = "" for i in range(n): if bold[i] and (i == 0 or not bold[i - 1]): ans += "" ans += text[i] if bold[i] and (i == n - 1 or not bold[i + 1]): ans += "" return ans ob = Solution() text = "thisissampleline" patterns = ["this", "ssam", "sample"] print(ob.solve(text, patterns))
Input
"thisissampleline", ["this", "ssam", "sample"]
Output
<b>this</b>i<b>ssample</b>line
- Related Questions & Answers
- Add Bold Tag in String in C++
- How to correctly enclose subquery in MySQL?
- Python Program to Print an Inverted Star Pattern
- Python program to print rangoli pattern using alphabets
- Python Program to print the pattern ‘G’
- Enclose a text to make it blink with HTML.
- How to print pattern in Python?
- How to use Bold & Non-Bold Text In A Single UILabel in iOS/iPhone?
- Python program to show diamond pattern with 2n-1 lines
- Phyllotaxis pattern in Python?
- Python program to convert Set into Tuple and Tuple into Set
- Program to print Interesting pattern in C++
- Program to print Kite Pattern in C++
- Program to print number pattern in C
- Program to print Diamond Pattern in C