We earn commission when you buy through affiliate links.
This does not influence our reviews or recommendations.Learn more.
In this tutorial, youll learn tocheck for valid parenthesesin Python.
Given a string of parentheses, checking if the parentheses combination isvalidis a popular coding interview question.
What is the Valid Parentheses Problem?
Lets start our discussion by answering the question,what is the valid parentheses problem?
In our problem-solving approach, the stack is the data structure thatll play a pivotal role.
Lets review the basics of a stack in the next section.
Lets proceed to solve the valid parentheses checking problem.
Step 1:Traverse the string from left to right.
Lets call the stringtest_str, and the individual characters in the stringchar.
Step 3.1:If its an opening bracket, push it again onto the stack.
Step 4.3:The final possibility is that the stack isempty.
Valid Parentheses String Examples Walkthrough
Now lets take three examples and walk through the above steps.
If youve already gotten the hang of how this works, feel free to skip to the next section.
Ive put together the following flowchart outlining the steps in the valid parentheses checking problem.
You may save it for quick reference!
In the next section, lets see how to translate our concept to Python code.
you might use the.append()method to add elements to the end of the list.
This is similar to pushing to the top of the stack.
As a next step, lets answer the question: how to differentiate between opening and closing brackets?
you’re free to use the.keys()method to access individual keys in the dictionary.
Lets use all that weve learned to write the definition of theis_valid()function.
Understanding the Function Definition
Read through the following code cell containing the function definition.
In addition, weve also added adocstringincluding:
You may usehelp(is_valid)oris_valid.__doc__to retrieve the docstring.
The Python functionis_validchecks if the parentheses string is valid, and it works as follows.
Now, lets go ahead and make a few function calls to verify that our function works correctly.
From the code snippet above, we can conclude that the function works as expected!
Conclusion
Heres a quick summary of what youve learned.
As a next step, make a run at code the problem onGeekflares online Python editor.
Feel free to revisit this guide if you need help!
Check out more Python tutorials.