Home > Software engineering >  Cant understand what this function does
Cant understand what this function does

Time:01-24

def is_balanced(input_str): s = list()

for ch in input_str:
    if ch == '(':
        s.append(ch)
    if ch == ')':
        if not s:
            return False
        s.pop()
return not s

Can anyone explain what is really happening after the line "if ch == ')':" ?

CodePudding user response:

if not s: checks whether the list is empty or not, if the list is empty then the condition inside is executed.

let's say you provide ())()() in input, so for:

-> the 0th index it will first add ( into s

-> for 1st index (i.e )): it will first check if s is empty or not, as here we have ( in s so the if condition will not execute, then it goes on to pop the value from the list. (notice now the list is empty)

-> on coming to the 2nd index (i.e )): it will first check if the list is empty or not, as the list is empty it will return False

  •  Tags:  
  • Related