URI Online Judge Solution 1068 Parenthesis Balance I using Python Programming Language.
Considering an expression with parenthesis, print a message informing if the among of parenthesis is correct or incorrect, without considering the rest of the expression. Example:
a+(b*c)-2-a is correct
(a+b*(2-c)-2+a)*2 is correct
when
(a*b-(2+c) is incorrect
2*(3-a)) is incorrect
)3+b*(2-c)( is incorrect
2*(3-a)) is incorrect
)3+b*(2-c)( is incorrect
Resuming, all closing parenthesis must have an open parenthesis and it's not possible a closing parenthesis without a previous open parenthesis, and the quantity of closing and open parenthesis must be the same.
Input
The input file contains N expressions (1 <= N <= 10000), each one with up to 1000 characters.
Output
The output must be correct or incorrect for each test case according with above rules.
Input Sample | Output Sample |
a+(b*c)-2-a
(a+b*(2-c)-2+a)*2 (a*b-(2+c) 2*(3-a)) )3+b*(2-c)( |
correct
correct
incorrect
incorrect
incorrect
|
Solution using Python :
while True:
try:
List1 = input()
List2 = []
correct = False
P1 = 0
P2 = 0
for v in List1:
if (v == '('):
P1 += 1
List2.append(v)
if (v == ')'):
P2 += 1
List2.append(v)
if(len(List2)%2 != 0):
correct = False
else:
if(List2[0] == ')'):
correct = False
else:
if (List2[len(List2) - 1] == '('):
correct = False
else:
if (P1 != P2):
correct = False
else:
correct = True
if(correct):
print("correct")
else:
print("incorrect")
except (EOFError):
break
Comments
Post a Comment