Home > Back-end >  Why the POP() function in condition can really remove the main Func?
Why the POP() function in condition can really remove the main Func?

Time:09-27

I have the following code, given a string s containing just the characters '(', ')', '{', '}', '[' and ']', and return True or False if

  1. Open brackets must be closed by the same type of brackets.
  2. Open brackets must be closed in the correct order.
  3. Every close bracket has a corresponding open bracket of the same type.
def isValid(s):
    stack = []

    open_bracket = ['(', '{', '[']
    close_bracket = [')', '}', ']']

    for i in s:
        if i in open_bracket:
            stack.append(i)
        if i in close_bracket:
            if stack == [] or close_bracket.index(i) != open_bracket.index(stack. Pop()):

                return False
    return (True if stack == [] else False)

Here is a question when I practice Leetcode.

Why the function use stack.Pop() in condition influence the list_stack?

 if stack == [] or close_bracket.index(i) != open_bracket.index(stack. Pop())

I can't get the picture. Why does it really remove the last item in stack?

The code comes from https://leetcode.com/problems/valid-parentheses/discuss/2601510/Python-Using-Stack-and-Index

CodePudding user response:

Why the function use stack.Pop() in condition influence the list stack?

if stack == [] or close_bracket.index(i) != open_bracket.index(stack. Pop())

I can't get the picture. Why does it really remove the last item in stack?

In Python expressions are evaluated from left to the right and logical conditions are only evaluated up to the value which is able to determine the final outcome.

In case of logical or if stack == [] would evaluate to True no further terms would be evaluated. If it evaluates to False there is at least one item in the list and the next term in or will be evaluated removing one item from the stack list in order to calculate one of the values which is needed for evaluation of the != condition.

The .pop() method works in-place on the list removing the last item from it and providing it as a return value. So the stack will be modified by .pop(), but this modification won't influence the outcome of boolean test on first term in or in case the stack becomes in this process an empty list because this term was already evaluated before and won't be evaluated again.

Why .pop()?. It is necessary to remove from stack the entry about an opening bracket in case a matching closing bracket is detected. This makes sure that all the opening brackets are removed from stack if there is an appropriate sequence of closing brackets.

  • Related