+ 3

Hi... plz help me in solving this...could not able to pass the all cases

s=str(input()) l1=[] l2=[] for v in s: if (v == "(" or v == "{" or v == "[" or v == "<"): l1.append(v) elif (v == ")" or v == "}" or v == "]" or v ==">"): l1.pop(0) else: l2.append(v) if l1==[]: print("True") else: print("False")

2nd Mar 2022, 8:14 AM
Krupa Varsha P
6 odpowiedzi
+ 3
Use 1 list as a stack. If you have an opening parentheses '(' then append() it to the stack. If you have a closing parentheses ')' and the stack is empty (len = 0) then return False, otherwise pop() the last element from the stack. When you have gone through all the parentheses that were input check if the stack is empty. If yes then True it is balanced, otherwise False it's not. You only need to check for parentheses for the module project. No curly braces or square brackets.
2nd Mar 2022, 9:01 AM
ChaoticDawg
ChaoticDawg - avatar
+ 1
Have you tried some unusual inputs whilst debugging? Eg: )((()()))(
2nd Mar 2022, 8:29 AM
HungryTradie
HungryTradie - avatar
+ 1
For example: Input is " (a} ", it will print True but need false. For the example: Your code, of if block if (v == "(" or v == "{" or v == "[" or v == "<"): l1.append(v) #pop " (" Into list but, By elif (v == ")" or v == "}" or v == "]" or v ==">"): l1.pop(0) # on "}", it will pop '(' , because you using "or" logical operator. you should split this to : only need to pop "(" when you see ")", and pop { when you see }, ... else: l2.append(v) #this is not required Here, problem only contains "(", ")" , other braces are included in input so fortunately your code may work for cases which don't cause pop on empty list. In this case, it raise error. Example: )( In this, cause on empty list, instead of pop, you should print false and stop proceedings.. s = str(input()) is same as s = input(), no need str(), it default accept as string type.. Hope it helps..
2nd Mar 2022, 7:45 PM
Jayakrishna 🇮🇳
+ 1
Ok 👍
3rd Mar 2022, 3:53 AM
Krupa Varsha P
0
Yeah but my code works for all ryt??
2nd Mar 2022, 9:00 AM
Krupa Varsha P
0
Yeah that only i did
2nd Mar 2022, 9:02 AM
Krupa Varsha P