Last answered:

25 Dec 2023

Posted on:

10 Aug 2022

0

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

Hi,

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

else:

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.

3 answers ( 0 marked as helpful)
Instructor
Posted on:

11 Aug 2022

2

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.
image.png
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.
image.png

Hope this helps!

Kind regards,
365 Hristina

Posted on:

11 Aug 2022

0

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!

Posted on:

25 Dec 2023

2

Hi Hristina, thanks for the detailed explanations. I have finally understood each line of the code. Keep up the great work! 

Submit an answer