Last answered:

11 Aug 2022

Posted on:

10 Aug 2022


I do not understand the second part of the solution, please help.


in the second part of the given solution, where we have:


if len(stack) == 0 or brackets[stack.pop()] != char:
                return False

return len(stack) == 0

I do not understand why it says brackets[stack.pop()]!=char.
please could you also clarify the return False and return len(stack) == 0?

Thank you very much for your help.

2 answers ( 0 marked as helpful)
Posted on:

11 Aug 2022


Hey Elisha,

Thank you for your question!

Let me paste a snapshot of the code here. In my explanation, I will refer to the line numbers from the snapshot.
1. Line 6 - We start by looping through the elements in the string s
2. Line 8 - If char matches any of the keys in the dictionary, namely (, [, or {, enter the if-statement
3. Line 9 - Append char to the stack list
4. Line 11 - If char doesn't match any of the dictionary keys, it should then match any of the dictionary values, namely ), ], or }
5. Line 12 - The first condition checks if the string s begins with a closing bracket. This is done by checking if the stack list is empty. If it's empty, then we've never appended neither (, nor [, nor {. Therefore, the string s begins with a closing bracket. This automatically implies that the string is not balanced. The if-statement returns False.
Let's now examine the second condition which, if true, also implies an imbalanced string. Remember that we entered this else-statement because char was a closing bracket, let's say }. stack.pop() returns the last bracket appended to the stack list and also removes it from the stack list. Therefore, since char = }, then we want the last appended bracket in stack to be its corresponding opening bracket - {. How do we check this? By asking whether brackets[ stack.pop() ] = }. If it's not, then we have to return False because the string is not balanced for sure.
6. Line 15 - If all closing brackets match their opening brackets, then we should be left with an empty stack list. That is so because we perform stack.pop() which removes the last element from the list. If stack is truly empty, then len(stack) == 0 would return True, which indicates a balanced string.

Below, I have added a couple of print-statements which could help you understand better the logic of the code.

Hope this helps!

Kind regards,
365 Hristina

Posted on:

11 Aug 2022


Hi Hristina

Thanks for the explanation. I think I understood your explanation, I need to practice more to make it sink faster in my head though! thank you!

Submit an answer