Exemplo n.º 1
0
class StackTest(unittest.TestCase):
    def setUp(self):
        self.s = Stack()

    def tearDown(self):
        while not self.s.isEmpty():
            self.s.pop()

    def test_push(self):
        value = 'A'
        self.s.push(value)
        self.assertEqual(1, self.s.size())
        print self.s.get()
        x = self.s.pop()
        print self.s.get()
        self.assertEqual(value, x)
        self.assertEqual(0, self.s.size())

    def test_peek(self):
        self.s.push('A')
        self.s.push('B')
        x = self.s.peek()
        self.assertEqual('B', x)
        self.assertEqual(2, self.s.size())

    def test_empty(self):
        self.assertEqual(self.s.peek(), None)
Exemplo n.º 2
0
def check_balance(string):
    '''
    Check to see if we have balanced parethesis.

    Parameters:
    -----------
    string: str. The string contains the text with parenthesis that needs to be check balanced.

    Return:
    Boolean. Tell if parenthesis is matched or not
    '''

    parethesis = Stack()
    par_dict = {')': '(', '}': '{', ']': '['}
    for s in string.strip():
        if s in par_dict.values():
            parethesis.push(s)
        elif s in par_dict.keys():
            try:
                t = parethesis.pop()
                if t != par_dict[s]:
                    return False
            except TypeError:
                return False
    if parethesis.size() != 0:
        return False

    return True