Sometimes, while working with Python data, we can have a problem in which we need to pair all the elements with the suitable closing brackets, and can have data associated with pairing. This kind of problem is classic application of Stack Data Structure and can have usage across many domains. Let’s discuss a certain way in which this task can be done.
Input : test_list = [(‘(‘, 1), (‘(‘, 2), (‘)’, 3), (‘)’, 4)]
Output : [(2, 3), (1, 4)]
Input : test_list = [(‘(‘, 1), (‘)’, 4)]
Output : [(1, 4)]
Method : Using stack DS + loop
The combination above functionalities can be used to solve this problem. In this, we make a new pair with each opening bracket and when the corresponding closing bracket comes using LIFO technique, we form a pair with that closing bracket.
The original list is : [('(', 7), ('(', 9), (')', 10), (')', 11), ('(', 15), (')', 100)] The paired elements : [(9, 10), (7, 11), (15, 100)]
Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.
To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning – Basic Level Course