示例#1
0
文件: stack_test.py 项目: dsovlk/ds
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)
def balancedparantheses(parantheses_string):
    s = Stack()
    balanced = True
    index = 0
    while index < len(parantheses_string) and balanced:
        symbol = parantheses_string[index]
        if symbol == "(":
            s.push(symbol)
        elif s.isEmpty():
            balanced = False
        else:
            s.pop()
        index += 1

    if balanced and s.isEmpty():
        return True
    else:
        return False
示例#3
0
def baseconverter(number, base):
    s = Stack()
    number_string = '0123456789ABCDEF'

    while number > 0:
        remainder = number % base
        s.push(remainder)
        number = number // base

    base_builder = ''
    while not s.isEmpty():
        base_builder = base_builder + str(number_string[s.pop()])

    return base_builder
def balancedsymbols(symbol_string):
    s = Stack()
    balanced = True
    index = 0
    lastopensymbol = ''
    while index < len(symbol_string) and balanced:
        symbol = symbol_string[index]
        lastopensymbol = s.peek()
        if symbol in "({[":
            s.push(symbol)
        elif s.isEmpty():
            balanced = False
        else:
            balanced = symbolchecker(lastopensymbol, symbol)
            if balanced:
                s.pop()

        index += 1

    if balanced and s.isEmpty():
        return True
    else:
        return False