w3resource

Python: Find a valid substring of s that contains matching brackets, at least one of which is nested

Python Programming Puzzles: Exercise-87 with Solution

Write a Python program to find a valid substring of a given string that contains matching brackets, at least one of which is nested.

Input: 
 ]][][[]]] 

Output:
[[]]

Input:  
]]]]]]]]]]]]]]]]][][][][]]]]]]]]]]][[[][[][[[[[][][][]][[[[[[[[[[[[[[[[[[ 

Output:
[[][][][]]
 

Visual Presentation:

Python: Find a valid substring of s that contains matching brackets, at least one of which is nested.

Sample Solution:

Python Code:

# License: https://bit.ly/3oLErEI

# Define a function named 'test' that takes a string 's' as input
def test(s):
    import re
    # Use regular expression to search for a valid substring with matching brackets
    return re.search(r"\[(\[\])+\]", s).group(0)

# Example 1
brackets1 = "]][][[]]]"
print("Original List of strings:", brackets1)
print("Find a valid substring of the said string that contains matching brackets, at least one of which is nested:")
print(test(brackets1))

# Example 2
brackets2 = "]]]]]]]]]]]]]]]]][][][][]]]]]]]]]]][[[][[][[[[[][][][]][[[[[[[[[[[[[[[[[["
print("\nOriginal List of strings:", brackets2)
print("\nFind a valid substring of the said string that contains matching brackets, at least one of which is nested:")
print(test(brackets2))

Sample Output:

Original List of strings: ]][][[]]]

Find a valid substring of the said string that contains matching brackets, at least one of which is nested:
[[]]

Original List of strings: ]]]]]]]]]]]]]]]]][][][][]]]]]]]]]]][[[][[][[[[[][][][]][[[[[[[[[[[[[[[[[[

Find a valid substring of the said string that contains matching brackets, at least one of which is nested:
[[][][][]]

Flowchart:

Flowchart: Python - Find a valid substring of s that contains matching brackets, at least one of which is nested.

Python Code Editor :

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

Previous: Find the vowels from each of the original texts (y counts as a vowel at the end of the word).
Next: Find an integer with the given number of even and odd digits.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://w3resource.com/python-exercises/puzzles/python-programming-puzzles-87.php