from stack import *
'''Brackets:
  () parentheses
  {} braces
  [] square brackets
  '''

def balanced(expr):
    '''Return True if expression expr has matching nested parentheses.'''
    
    # ()    ()()   (()())    (()
    s = Stack()
    
    balanced_so_far = True
    i = 0
    while balanced_so_far and i < len(expr):
        next = expr[i]
        if next == "(":
            s.push(next)
        elif not s.isEmpty():
            s.pop()
        else:
            balanced_so_far = False
        i = i+1
    
    return balanced_so_far and s.isEmpty()

print balanced("((()))")      # should be True
print balanced("((())))")     # should be False
print balanced("((())")       # should be False
