Question: This is a part of my python code, I need to scan a java file to check if it has balanced parenthesis or not, but
This is a part of my python code,
I need to scan a java file to check if it has balanced parenthesis or not, but I can't get correct result, can you debug for me?
I use stack to store the parenthesis that I found and pop the stack if there is a match.

with open("Sample.java", "r") as src: stack = [] left = ["[", "{", "("] right = ["]", "}", ")"] balanced = True for line2 in src: for ch2 in line2: if ch2 in left: stack.append(ch2) elif ch2 in right: pos = right.index(ch2) if(len(stack) > @) and (left[pos] == stack[len(stack) - 1]): stack.pop() else: balanced = False if len(stack) == 0: balanced = True if balanced == True: print("balanced") else: print("unbalanced") with open("Sample.java", "r") as src: stack = [] left = ["[", "{", "("] right = ["]", "}", ")"] balanced = True for line2 in src: for ch2 in line2: if ch2 in left: stack.append(ch2) elif ch2 in right: pos = right.index(ch2) if(len(stack) > @) and (left[pos] == stack[len(stack) - 1]): stack.pop() else: balanced = False if len(stack) == 0: balanced = True if balanced == True: print("balanced") else: print("unbalanced")
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
