I'm writing a program that determines whether a math equation input by user has matching parentheses. I have it to where it counts whether the amount of right parentheses are equal to the amount of left parentheses, but the user could input 2) (3+x)(4+x) (6. To avoid telling the user his parentheses match in this case, I want to check if a ')' comes before a '('.
left_parenth = math.count("(")
right_parenth = math.count(")")
total_parenth = right_parenth + left_parenth
if total_parenth % 2 != 0:
if right_parenth > left_parenth:
print("\nYou are missing a left parentheses '('")
elif right_parenth < left_parenth:
print("\nYou are missing a right parentheses ')'")
elif total_parenth % 2 == 0:
print("\nYour equation has the correct amount of parentheses")
General idea here is to use stack. When you encounter a opening parentheses, PUSH it on stack When you encounter a closing parentheses, POP cooresponding opening parentheses from stack
Using a stack is definitely not necessary. Just keep a count of how many parentheses are open. If that count ever is negative, then they aren't matched, and if the count ends up positive, they aren't matched:
def valid_parens(string):
open_count = 0
for char in string:
if char == "(":
open_count += 1
elif char == ")":
open_count -= 1
if open_count < 0:
return False
return open_count == 0
Test cases:
assert valid_parens("((2+2)-4)*2") == True
assert valid_parens(")(2/2)(") == False
assert valid_parens("()()()") == True
assert valid_parens("((())") == False
Although the problem can be solved with a stack, it's a little wasteful of memory. In normal-sized inputs this wouldn't ever be a problem, but in really large sequences it would become a problem. You don't need to keep track of the parens themselves, but just a count of how many open ones there are -- total memory usage is a single integer, rather than one entry on a stack per paren encountered.
def proper_paren(seq):
open_parens = 0
for char in seq:
if char == '(':
open_parens += 1
elif char == ')':
open_parens -= 1
if open_parens < 0:
return False
return open_parens == 0
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.