Someone can explain me why this code is correct in Balanced Parentheses? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

Someone can explain me why this code is correct in Balanced Parentheses?

def balanced(expression): count = 0 for char in expression: if char == "(": count += 1 elif char == ")": if count == 0: return False count -= 1 return count == 0 print(balanced(input()))

24th Aug 2022, 10:09 PM
Josué Varela
Josué Varela - avatar
1 Answer
+ 2
Hi! because you have this algorithm for the program. when the left bracket occurs, the counter is incremented by 1, when the right -> 1 is taken away. the function returns when the balance of brackets matches (and it matches when their equal number and the counter is zero)
24th Aug 2022, 10:44 PM
Yaroslav Vernigora
Yaroslav Vernigora - avatar